合併排序法-Java實現
阿新 • • 發佈:2018-12-22
public static void mergeSort(int[] a, int low, int high) { //呼叫mergeSort方法時low為0, high為a.length-1 int mid = (low + high) / 2; if (low < high) { MergeSort(a, low, mid); MergeSort(a, mid + 1, high); merge(a, low, mid, high); } } public static void merge(int[] a, int low, int mid, int high) { int[] temp = new int[high - low + 1]; int i = low; int j = mid + 1; int k = 0; while (i <= mid && j <= high) { if (a[i] < a[j]) temp[k++] = a[i++]; else temp[k++] = a[j++]; } while (i <= mid) temp[k++] = a[i++]; while (j <= high) temp[k++] = a[j++]; for (int index = 0; index < temp.length; index++) a[index + low] = temp[index]; }