將數組分爲2塊,再到每一小塊再分爲兩塊,直到最後一個元素爲一塊,而後進行有序數組合並,最終合併爲一個有序數組
代碼實現數組
public static void mergeSorts ( int[] array){ mergeSortsInternal(array,0,array.length) //mergeSortsInternalNoR(array); } /** * 歸併排序:遞歸內部排序 */ public static void mergeSortInternal ( int[] array, int low, int high){ if (low + 1 >= high) {//[low,high) return; } int mid = (low + high) / 2; mergeSortInternal(array, low, mid); mergeSortInternal(array, mid, high); merge(array, low, mid, high); } private static void merge ( int[] array, int low, int mid, int high){ int length = high - low; int[] extral = new int[length]; //[low,mid] //[mid,high] int less = low; int great = mid; int i = 0; while (less < mid && great < high) { if (array[less] <= array[great]) { extral[i] = array[less]; less++; i++; } else { extral[i] = array[great]; great++; i++; } } while (less < mid) { extral[i++] = array[less++]; } while (great < high) { extral[i++] = array[great++]; } for (int j = 0; j < length; j++) { array[low + j] = extral[j]; } }