基本思想:將若干有序序列逐步歸併,最終歸併成一個有序序列。 java
基本思想:將序列分爲若干有序序列(開始爲單個記錄),兩個相鄰有序的序列合併成一個有序的序列,重複進行,直到整個序列有序。 數組
一次歸併過程:兩個有序序列a、b,目標數組c。每次往目標數組c中放一個記錄,a、b序列誰小就放誰。直到一個數組所有放入目標數組,對另外一個進行收尾工做。 blog
歸併的遞歸實現: 排序
/** * 將兩個數組合並,每次往目標數組中放一個元素,誰元素小就放誰<br> * 直到一個數組所有放入目標數組,對另外一個進行收尾工做。<br> * * @param arr1 * @param arr2 * @return */ public static int[] mergeArray(int[] arr1, int[] arr2) { int size1 = arr1.length; int size2 = arr2.length; int[] temp = new int[size1 + size2];//目標數組 int i = 0, j = 0, k = 0; while (i < size1 && j < size2) {// 直到一個數組所有放入目標數組 if (arr1[i] < arr2[j]) temp[k++] = arr1[i++]; else temp[k++] = arr2[j++]; } MyPrinter2.printArr(temp); // 收尾工做 while (i < size1) temp[k++] = arr1[i++]; while (j < size2) temp[k++] = arr2[j++]; MyPrinter2.printArr(temp); return temp; }
/** * 將兩個相鄰的有序區間source[first~mid],source[mid+1~last]合併到temp數組中<br> * * @return */ public static void merge(int[] source, int[] temp, int first, int mid, int last) { int i = first, j = mid + 1; int k = 0; while (i <= mid && j <= last) {// 直到一個數組所有放入目標數組 if (source[i] < source[j]) temp[k++] = source[i++]; else temp[k++] = source[j++]; } // 收尾工做 while (i <= mid) temp[k++] = source[i++]; while (j <= last) temp[k++] = source[j++]; // 將歸併結果放入原數組中。 for (i = 0; i < k; i++) source[first + i] = temp[i]; } public static void mergeSort(int[] source, int[] temp, int first, int last) { if (first < last) { int mid = (first + last) / 2; mergeSort(source, temp, first, mid); //歸併排序前半個子序列 mergeSort(source, temp, mid + 1, last); //歸併排序後半個子序列 merge(source, temp, first, mid, last); } else if (first == last) { //待排序列只有一個,遞歸結束 temp[first] = source[first]; } } public static void msort(int[] arr) { int size = arr.length; int[] temp = new int[size]; mergeSort(arr, temp, 0, size - 1); //此時temp與arr同樣,都是已排序好的序列。 }