归并排序:利用递归与分治技术将数据序列划分成为越来越小的半子表,在对半子表排序后,再用递归方法将排好的半子表合成为越来越大的有序序列。
例子:
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;
}