归并排序
将一个数组递归地分成两半分别排序,然后将结果归并起来。
自顶向下归并排序
public class Merge extends Sort {
private static Comparable[] aux;
public static void sort(Comparable[] a) {
aux = new Comparable[a.length];
sort(a, 0, a.length - 1);
}
private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
protected static void merge(Comparable[] a, int lo, int mid, int hi) {
int i = lo, j = mid + 1;
// 数组复制
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[j], aux[i])) a[k] = aux[j++];
else a[k] = aux[i++];
}
}
}
自顶向下归并排序
public class MergeBU extends Merge {
private static Comparable[] aux;
public static void sort(Comparable[] a){
aux = new Comparable[a.length];
int N = a.length;
for (int sz = 1; sz < N; sz = sz * 2){
for(int lo = 0; lo < N - sz; lo += sz * 2){
merge(a, lo, lo + sz - 1, Math.min(lo + sz * 2 - 1, N - 1));
}
}
}
}
结论
对于长度为N的任意数组,归并排序需要1/2NlgN至NlgN次比较。
网友评论