折半插入排序,c/c++描述

  折半插入排序和直接插入排序是一样的。都是把未定位的元素插入到已排好序的数组里。不同的是对插入位置的查找方法不同。直接插入是比较关键字一次,插入一次。折半插入是折半二分比较得到最终插入位置后,集体移动数组元素,空出待插入位置,再插入新的元素。
  还有一个难点就是折半查找后,对最终插入位置的下标的确定。需要仔细思考,对照,因为仅差一位。
全部代码如下:

#include<iostream>
using namespace std;

void binaryInsertSort(int array[],int length) {
	int temp, indexSmall, indexLarge,indexMid;
	for (int i = 1; i < length; i++) {
		temp = array[i];

		indexSmall = 0;
		indexLarge = i - 1;
	
		while (indexSmall <= indexLarge){
			indexMid = (indexSmall + indexLarge) / 2;

			if (temp > array[indexMid])
				indexSmall = indexMid + 1;
			else
				indexLarge = indexMid - 1;
		}  //  进过仔细比对,插入位置是 indexSmall

		for (int j = i; j >= indexSmall + 1; j--)
			array[j] = array[j - 1];

		array[indexSmall] = temp;
	}

	for (int i = 0; i < length; i++)
		cout << array[i] << ' ';
}

int main() {
	int array[] = { 1,5,2,4,6,3,0,7,9,8 }, length = 10;

	binaryInsertSort(array,length);

	return 0;
}

测试结果如下:
在这里插入图片描述
谢谢阅读。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值