歸併排序 遞迴與非遞迴實現
阿新 • • 發佈:2019-02-06
歸併排序:要將一個數組排序,可以先(遞迴地)將他分成兩半分別排序,然後將結果歸併起來。
時間複雜度 O(NlogN)
空間複雜度 O(N)
自頂向下,通過遞迴實現:
package sort;
import edu.princeton.cs.algs4.StdRandom;
public class MergeSort extends BaseSort{
private static Comparable[] aux;
public static void sort(Comparable[] a) {
aux = new Comparable[a.length];
sort(a,0 ,a.length-1);
}
public 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);
}
public static void merge(Comparable[] a ,int lo,int mid,int hi) {
int i = lo;
int 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 static void main(String[] args) {
int N = 30;
Double[] a = new Double[N];
for(int i=0;i<N;i++)
a[i] = StdRandom.uniform();
sort(a);
}
}
自底向上,非遞迴實現:
public static void sort(Comparable[] a) {
int N = a.length;
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, lo, lo+sz-1,Math.min(lo+sz+sz-1, N-1));
tools.draw((Double[]) a);
}
}
}