标签:
基本排序:归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
1 public static void main(String[] args){ 2 int a[] = {34, 8, 64, 51, 32, 21}; 3 mergeSort(a, 0, a.length-1); 4 for (int i = 0; i < a.length; i++) { 5 System.out.print(a[i] + " "); 6 } 7 } 8 9 public static void mergeSort(int[] a, int left, int right) { 10 if (left < right) { 11 int center = (left+right)/2; 12 mergeSort(a, left, center); 13 mergeSort(a, center+1, right); 14 merge(a, left, center, right); 15 } 16 } 17 18 public static void merge(int[] a, int left, int center, int right) { 19 int[] tmpArr = new int[a.length]; 20 int mid = center+1; 21 int third = left; 22 int tmp = left; 23 24 while (left <= center && mid <= right) { 25 if (a[left] <= a[mid]) { 26 tmpArr[third++] = a[left++]; 27 } else { 28 tmpArr[third++] = a[mid++]; 29 } 30 } 31 while (mid <= right) { 32 tmpArr[third++] = a[mid++]; 33 } 34 while (left <= center) { 35 tmpArr[third++] = a[left++]; 36 } 37 38 while (tmp <= right) { 39 a[tmp] = tmpArr[tmp++]; 40 } 41 }
标签:
原文地址:http://www.cnblogs.com/daemonspirit/p/4685176.html