java实现的排序(插入/希尔/归并)
java实现三种简单的排序,以下是代码:
1 /*插入排序*/ 2 public static void insertionSort(int[] a) 3 { 4 int j; 5 for(int p = 1; p < a.length; p++) 6 { 7 int tmp = a[p]; 8 for(j = p; j > 0 && tmp < a[j - 1]; j--) 9 a[j] = a[j - 1]; 10 a[j] = tmp; 11 } 12 13 } 14 //----------------------------------------------------------- keleyi.com 15 /*希尔排序*/ 16 public static void shellsort(int[] a) 17 { 18 int j; 19 20 for(int gap = a.length / 2; gap > 0; gap /= 2) 21 for(int i = gap; i < a.length; i++) 22 { 23 int tmp = a[i]; 24 for(j = i; j >= gap && tmp < a[j - gap]; j-=gap) 25 a[j] = a[j - gap]; 26 a[j] = tmp; 27 } 28 } 29 //----------------------------------------------------------- 30 /*归并排序*/ 31 private static void mergeSort(int []a, int []tmpArray, int left, int right) 32 { 33 if(left < right) 34 { 35 int center = (left + right) / 2; 36 mergeSort(a, tmpArray, left, center); 37 mergeSort(a, tmpArray, center + 1, right); 38 merge(a, tmpArray, left, center + 1, right); 39 } 40 } 41 public static void mergeSort(int []a) 42 { 43 mergeSort(a, tmpArray, 0, a.length - 1); 44 }