int i = lo; j = mid + 1; for(int k=lo;k<=hi;k++){ //merge from a[] to aux[] if(i > mid) aux[k] = a[j++]; elseif(j > hi) aux[k] = a[i++]; elseif(less(a[j],a[i])) aux[k] = a[j++]; else aux[k] = a[i++]; }
}
privatestaticvoidsort(Comparable[] a,Comparable[] aux,int lo,int hi){ //assumes aux[] is initialize to a[] once,before recursive calls. if(hi <= lo) return; int mid = lo + (hi - lo) / 2; // switch roles of aux[] and a[] sort(aux,a,lo,mid); sort(aux,a,mid+1,hi); merge(a,aux,lo,mid,hi); }
bottom-up mergesort
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassMergeBU{ privatestaticvoidmerge(...){ /* as before */ }
publicstaticvoidsort(Comparable[] a){ int N = a.length; Comparable[] aux = new Comparable[N]; for (int sz = 1; sz < N; sz = sz+sz) for (int lo = 0; lo < N-sz; lo += sz+sz) merge(a, aux, lo, lo+sz-1, Math.min(lo+sz+sz-1, N-1));
} }
Bottom line.Simple and non-recursive version of mergesort.but about 10% slower than recursive,top-down mergesort on typical systems.