所以我有一個MergeSort算法,我想結合MergeSort和插入排序來減少合併的開銷,問題是如何?我想使用插入排序對段進行排序,然後合併。MergeSort與插入排序組合,使其更有效
public class mergesorttest{
public static void main(String[]args){
int d[]= {10,2,3,4,5,6,5,4,3,5,6,7,1};
mergeSort(d,0,d.length);
for(int x:d) System.out.print(x+" ");
System.out.println();
}
static void mergeSort(int f[],int lb, int ub){
//termination reached when a segment of size 1 reached -lb+1=ub
if(lb+1<ub){
int mid = (lb+ub)/2;
mergeSort(f,lb,mid);
mergeSort(f,mid,ub);
merge(f,lb,mid,ub);
}
}
static void merge (int f[],int p, int q, int r){
//p<=q<=r
int i =p; int j = q;
//use temp array to store merged sub-sequence
int temp[] = new int[r-p]; int t = 0;
while(i<q && j<r){
if(f[i]<=f[j]){
temp[t] =f[i];
i++;t++;
}
else{
temp[t] = f[j];
j++;
t++;
}
//tag on remaining sequence
while(i<q){
temp[t] = f[i];
i++;
t++;
}
while(j<r){
temp[t]=f[j];
j++;
t++;
}
//copy temp back to f
i=p;t=0;
while(t<temp.length){
f[i]=temp[t];
i++;
t++;
}
}
}
}
public static void insertion_srt(int array[], int n, int b){
for (int i = 1; i < n; i++){
int j = i;
int B = array[i];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
}
}
這是一個很好的答案,雖然它有助於理解大O理論,並解釋最佳案例/最壞案例/平均案例。 – 2013-02-25 08:37:34
值得一提的是,這正是內置JDK排序的工作方式 - 對於數組<7,它執行插入排序,對於> 7,它執行mergesort。 – 2013-02-25 08:58:37
我以爲'Collections.sort()'爲更大的集合使用快速排序。 – bdares 2013-02-25 09:00:53