public class MergeSortDemo { public static void mergeSort(int[] data) { if (null == data || data.length == 0) { return; } mergeSort(data, 0, data.length - 1); } private static void mergeSort(int[] data, int start, int end) { if (start >= end) return; int middle = (start + end) >> 1; mergeSort(data, start, middle); mergeSort(data, middle + 1, end); mergeData(data, start, middle, end); } private static void mergeData(int[] data, int start, int middle, int end) { int length = end - start + 1; int[] tempData = new int [length]; int left = start; int right = middle + 1; int all = 0; while (right <= end) { while (left <= middle && data[left] <= data[right]) { tempData[all++]=data[left++]; } if (left > middle) break; while (right <= end && data[left] > data[right]) { tempData[all++] = data[right++]; } } if (left <= middle) { System.arraycopy(data, left, tempData, all, middle - left + 1); } if (right <= end) { System.arraycopy(data, right, tempData, all, end - right + 1); } System.arraycopy(tempData, 0, data, start, tempData.length); } public static int[] genNumCollection(int length) { if(length <1) return null ; int[] data = new int[length]; Random r = new Random(); for (int i = 0; i < length; i++) { data[i]= r.nextInt(100); } return data; } public static void main(String[] args) { int[] data = genNumCollection(10); mergeSort(data); for (int i = 0; i < data.length; i++) { System.out.print(data[i]+" "); } } }
合并排序(MergeSort)的原理是对一个长度为 N 的元素序列 , 将其看成是 N 个独立的有序的序列,每次对长度为 d 的 “ 有序” 序列进行合并,直到 d == N ;