public void mergeSort(int[] array) {
int n = array.length;
for (int length = 1; length < n; length = 2 * length)
mergePass(array, length, n);
}
public void mergePass(int[] array, int length, int n) {
int i;
for (i = 0; i + 2 * length - 1 < n; i = i + 2 * length) {
merge(array, i, i + length - 1, i + 2 * length - 1);
}
if (i + length - 1 < n)
merge(array, i, i + length - 1, n - 1);
}
public void merge(int[] array, int low, int mid, int high) {
int i = low, j = mid + 1;
int k = 0;
int[] temps = new int[high - low + 1];
while (i <= mid && j <= high) {
if (array[i] <= array[j]) {
temps[k++] = array[i++];
} else {
temps[k++] = array[j++];
}
}
while (i <= mid) {
temps[k++] = array[i++];
}
while (j <= high) {
temps[k++] = array[j++];
}
for (k = 0, i = low; i <= high; i++, k++)
array[i] = temps[k];
}
归并排序
最新推荐文章于 2024-08-12 19:32:44 发布