Java中数组常见的几种排序方法!
数组的定义:
int[] arr = new int[5]; int[] arr1 = {1,2,3,4,5}; long[] arr2 = new long[6]; String[] strs = new String[5]; Person[] ps = new Person[5];
数组的操作:
int[] arr = {45, 34, 53, 43}; Arrays.sort(arr); System.out.println(Arrays.toString(arr)); // 二分搜索法(使用之前需要先排序) int i = Arrays.binarySearch(arr, 34); System.out.println(i); int[] newArr = Arrays.copyOf(arr, 7); int[] newArr1 = Arrays.copyOfRange(arr, 1, 3); System.out.println(Arrays.toString(newArr)); System.out.println(Arrays.toString(newArr1)); int j = Arrays.binarySearch(arr, 1, 3, 34); System.out.println(j);
冒泡排序:
int[] arr = {23,12,48,56,45};
int temp = -1; for(int i=0;i<arr.length;i++) { for(int j=i+1;j<arr.length;j++) { if(arr[i]>arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } System.out.println(Arrays.toString(arr));
直接选择排序:
int[] arr = {23,12,48,56,45};
for(int i=0;i<arr.length;i++) { int tem = i; for(int j=i;j<arr.length;j++) { if(arr[j] < arr[tem]) { tem = j; } } int temp1 = arr[i]; arr[i] = arr[tem]; arr[tem] = temp1; } System.out.println(Arrays.toString(arr));
反转排序:
int[] arr = {23,12,48,56,45};
for(int i=0;i<arr.length / 2;i++) { int temp = arr[i]; arr[i] = arr[arr.length-i-1]; arr[arr.length-i-1] = temp; } System.out.println(Arrays.toString(arr))