黑马程序员 自己写了个DataSorter类
? ? -------?android培训、java培训、期待与您交流! ----------
?
? ? 自己写了一个DataSorter类,对数组进行排序,虽然在实际开发中没什么用,但十分锻炼思维。供大家参考一下。
public class DataSorter {public static void main(String[] args) {int[] arr = {8,7,6,5,4,3,2,1};shellSort(arr);print(arr);}public static void bubbleSort(int[] arr) { for(int i = 0; i < arr.length - 1; i++) { for(int j = 0; j < arr.length - 1 - i; j++) { if(arr[j] > arr[j + 1]) { arr[j] = arr[j] ^ arr[j + 1];arr[j + 1] = arr[j] ^ arr[j + 1];arr[j] = arr[j] ^ arr[j + 1];}}}}public static void selectionSort(int[] arr) {int tmp;for(int i = 0; i < arr.length - 1; i++) { tmp = i;for(int j = i + 1; j < arr.length; j++) if(arr[tmp] > arr[j])tmp = j;if(tmp != i){arr[i] = arr[i] ^ arr[tmp];arr[tmp] = arr[i] ^ arr[tmp];arr[i] = arr[i] ^ arr[tmp];}}}public static void insertionSort(int[] arr) {int tmp; for(int i = 0; i < arr.length - 1; i++) {tmp = arr[i+1];for(int j = i; j >= 0; j--){if(arr[j] > tmp)arr[j + 1] = arr[j];else{arr[j + 1] = tmp;break;}}}}public static void shellSort(int[] arr) {for (int group = arr.length / 2; group > 0; group /= 2){for (int i = group; i < arr.length; i++){for (int j = i - group; j >= 0; j -= group){if (arr[j] > arr[j + group]){arr[j] = arr[j] ^ arr[j + group];arr[j + group] = arr[j] ^ arr[j + group];arr[j] = arr[j] ^ arr[j + group];}}}}}public static void quickSort(int[] arr){quickSort(arr,0,arr.length - 1);}public static void quickSort(int[] arr,int start,int stop) {int tmp = arr[start],i = start,j = stop;while(i < j){if(arr[i + 1] > tmp){while(i < j){if(arr[j] < tmp){arr[i] = arr[j];break;}elsej--;}if(i < j){i++;arr[j] = arr[i];j--;}}else{arr[i] = arr[i + 1];i++;} }if(i > start) arr[i] = tmp;if(i > start + 1) quickSort(arr,start,i - 1);if(i < stop - 1) quickSort(arr,i + 1,stop);}public static void print(int[] arr) {for(int i = 0; i < arr.length; i++) {System.out.print(arr[i] + " ");}System.out.println(); } }
?