歸併排序:利用遞歸與分治技術將數據序列劃分成爲越來越小的半子表,在對半子表排序後,再用遞歸方法將排好的半子表合成爲越來越大的有序序列。
例子:
8 | 2 | 1 | 6 | 5 | 7 | 4 | 3 |
拆分:
左子樹:
8 | 2 | 1 | 6 |
右子樹:
5 | 7 | 4 | 9 |
繼續拆分:
左子樹:
8 | 2 |
右子樹:
1 | 6 |
左子樹:
5 | 7 |
右子樹:
4 | 9 |
合併:
第一輪:
2 | 8 |
1 | 6 |
5 | 7 |
4 | 9 |
第二輪:
1 | 2 | 6 | 8 |
4 | 5 | 7 | 9 |
第三輪:
1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 |
代碼如下:
//歸併排序
private int[] MergeSort(int array[]) {
if (array.length < 2) return array;
//切分位置
int mid = array.length / 2;
int[] left = Arrays.copyOfRange(array, 0, mid);
int[] right = Arrays.copyOfRange(array, mid, array.length);
return merage(MergeSort(left), MergeSort(right));
}
//合併
private int[] merage(int[] lefts, int[] rights) {
//存放合併的新數組
int[] result = new int[lefts.length + rights.length];
for (int index = 0, leftIndex = 0, rightIndex = 0; index < result.length; index++) {
if (leftIndex >= lefts.length) {
result[index] = rights[rightIndex++];
} else if (rightIndex >= rights.length) {
result[index] = lefts[leftIndex++];
} else if (lefts[leftIndex] >= rights[rightIndex]) {
result[index] = rights[rightIndex++];
} else {
result[index] = lefts[leftIndex++];
}
}
return result;
}