折半插入排序——基于直接插入排序

2019-08-07
基本思想.PNG

排序过程.PNG

排序过程2.png

原理.PNG

CODE.PNG

代码实现

/**
 * @Date: 2019/8/7 09:08
 * @Description: 折半插入排序,对直接插入排序中
 * i前面的基本有序序列使用折半查找来寻找合适的插入位置
 */
public class BinsertSort {
    public void binsertSort(int[] a) {

        int length = a.length;//数组长度,将这个提取出来是为了提高速度
        int insertNum;//要插入的数

        //i从第二个数开始向后遍历
        for (int i = 1; i < length; i++) {
            insertNum = a[i];//要插入的数

            //对i前面的序列进行折半查找,找出插入位置
            int low = 0, high = i - 1;
            while (low <= high) { //比较,折半查找寻找合适的插入位置low
                int mid = (low + high) / 2;
                if (insertNum < a[mid])//插入到在低半区
                    high = mid - 1;
                else //插入到在高半区
                    low = mid + 1;
            }

            //将插入位置low之后的元素向后移动
            for (int j = i - 1; j >= low; --j)
                a[j + 1] = a[j];
            a[low] = insertNum;//将要插入的数插入到合适的位置

        }

        System.out.println(Arrays.toString(a));
    }

    @Test
    public void testBinsertSort() {
        int[] a = {35, 11, 24, 52, 77, 69, 8, 3, 6, 62};
        int[] b = {7, 9, 3, 2, 5, 8, 6};
        binsertSort(a);
        binsertSort(b);
    }
}
/*
Output:
[3, 6, 8, 11, 24, 35, 52, 62, 69, 77]
[2, 3, 5, 6, 7, 8, 9]
 */

算法分析.PNG

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值