首先将待排序的元素序列分成两个长度相等的子序列,为每一个子序列排序,然后再将它们合并成一个序列。
private void mergeSort(int[] a, int[] b, int left, int right) {
if (left < right) {
int middle = (left + right) / 2;
mergeSort(a, b, left, middle);
mergeSort(a, b, middle + 1, right);
merge(a, b, left, middle, right);
}
}
private void merge(int[] a, int[] b, int left, int middle, int right) {
if (left < right) {
int p, q, t;
p = left;
q = middle + 1;
t = left;
while (p <= middle && q <= right) {
if (a[p] <= a[q]) {
b[t++] = a[p++];
} else
b[t++] = a[q++];
}
while (p <= middle)
b[t++] = a[p++];
while (q <= right)
b[t++] = a[q++];
for (int k = left; k < t; k++)
a[k] = b[k];
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/jlqcloud/article/details/46940031