BRANDXYF 2022-08-10 17:32 采纳率: 100%
浏览 61
已结题

普通的插入排序比二分插入排序要更快

普通的插入排序比二分插入排序要更快,为什么会这样?

使用10万个随机数测试,普通插入排序752毫秒左右,二分插入排序1928毫秒左右

import java.util.Arrays;
import java.util.Random;

public class Sort {

    public static void insertSort(int[] a){
        int n = a.length;
        int cur;
        int j;
        for(int i=1;i<n;i++){
            cur = a[i];
            for(j=i-1;j>=0;j--){
                if(a[j] > cur){
                    a[j+1] = a[j];
                }
                else{
                    break;
                }
            }
            a[j+1] = cur;
        }
    }

    public static void binInsertSort(int[] a){

        int c;
        int insertValue;
        int insertIndex;
        int n = a.length;
        for(int i=1;i<n;i++){

            insertValue = a[i];
            insertIndex = bSearch1(a,i-1,insertValue);


            for(c=i-1;c>=insertIndex+1;c--){
                a[c+1] = a[c];
            }
            a[insertIndex+1] = insertValue;

        }

    }


    public static int bSearch1(int[] a, int n, int key){
        int low = 0;
        int high = n;
        int mid;
        while(low<=high){
            mid = low + ((high-low)>>1);
            if(a[mid] <= key){
                if(mid==n || a[mid+1]>key){
                    return mid;
                }
                low = mid + 1;
            }else {
                high = mid - 1;
            }
        }
        return -1;
    }

    public static int bSearch2(int[] a, int n, int key){
        int low = 0;
        int high = n;
        int mid;
        while(low<=high){
            mid = low + ((high-low)>>1);
            if(a[mid] == key){
                return mid;
            }else if(a[mid] > key){
                high = mid - 1;
            }else {
                low = mid + 1;
            }
        }
        return low - 1;
    }


    public static void main(String[] args) {
        int n = 100000;
        int[] a1 = new int[n];
        int[] a2 = new int[n];
        for(int i=0;i<n;i++){
            int t = new Random().nextInt(n);
            a1[i] = t;
            a2[i] = t;
        }

        long l = System.currentTimeMillis();
        insertSort(a1);
        System.out.println(System.currentTimeMillis()-l);
        l = System.currentTimeMillis();
        binInsertSort(a2);
        System.out.println(System.currentTimeMillis()-l);


    }

}
  • 写回答

2条回答 默认 最新

  • 快乐鹦鹉 2022-08-10 17:41
    关注

    根本没看见binInsertSort函数在哪

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 8月18日
  • 已采纳回答 8月10日
  • 修改了问题 8月10日
  • 创建了问题 8月10日

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?