【问题标题】:Combining Merge Sort with Insertion Sort合并排序与插入排序相结合
【发布时间】:2015-10-03 18:49:10
【问题描述】:

有人可以告诉为什么当阈值设置为

输入:{20、19、18、17、16、15、14、13、12、11、10、9、8、7、6、5、4、3、2、1};输出:{3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2 1 }

public class mergesorttest{
    public static void main(String[]args){
        int d[]= {20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
        mergeSort(d,0,d.length);
        for(int x:d) System.out.print(x+" "); 
        System.out.println(); 
    }

    static final int THRESHOLD = 3;
    static void mergeSort(int f[],int lb, int ub){
        if (ub - lb <= THRESHOLD)
            insertion_srt(f, lb, ub);
        else
        {
            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;
     }
    }
}

附:代码是从其他帖子借来的 Combining MergeSort with Insertion sort to make it more efficient

【问题讨论】:

    标签: java sorting mergesort insertion-sort


    【解决方案1】:

    insertion_srt() 中的 for 循环不应该是

        for (int i = n+1; i < b; i++){
    

    还有while循环:

            while ((j > n) && (array[j-1] > B)){
    

    merge() 也需要修复,第一个 while 循环的尾括号需要在代码之前向上移动以标记剩余序列:

        while(i<q && j<r){
            if(f[i]<=f[j]){
                temp[t] =f[i]; 
                i++;
                t++;
            }else{
                temp[t] = f[j];
                j++;
                t++;
            }
        }
        while(i<q){
            temp[t] = f[i];
            i++;
            t++;
        }
        while(j<r){
            temp[t]=f[j];
            j++;
            t++;
        }
    

    【讨论】:

    • 如果根据您的说明更改了 insert_srt() ,则输出的排序会更差。输入:{20、19、18、17、16、15、14、13、12、11、10、9、8、7、6、5、4、3、2、1} 输出:{1 11 16 19 20 17 18 14 15 12 13 6 9 10 7 8 4 5 2 3 }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2019-09-09
    • 2021-02-03
    • 2018-03-08
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    相关资源
    最近更新 更多