插入排序-折半插入排序

折半插入排序

一、定义

    由于插入排序的基本操作是在一个有序表中进行查找和插入,那对于在有序表中查找新记录的插入位置就可以使用二分查找来实现,此时进行的插入排序叫折半插入排序。时间复杂度为o(n^2)。

二、实现

    使用两个指针low、high分别指向有序表的开始和结束,求取中间位置mid = (low+ high)/ 2,然后比较待插入记录,若其小于list[mid],则插入位置在[low,mid - 1]区间,反之,则在[low + 1,high]区间,循环直至找到插入位置(low 或 high + 1)。
在这里插入图片描述

void binary_sort(ElementType list[],int n){
    
    
	ElementType temp;
	int i,j,low,high,mid;
	for(i = 1; i < n;i++){
    
    //n - 1趟插入
	    low = 0 ;
		high = i - 1;
		temp = list[i];

		while(low <= high){
    
    //寻找插入位置
		    mid = (low + high) / 2;
			if(temp < list[mid]) high = mid - 1;
			else low = mid + 1;
		}
		//移动
		for(j = i - 1;j >= high + 1;j--) list[j + 1] = list[j];
        //插入
		list[high + 1] = temp;
	}
}

猜你喜欢

转载自blog.csdn.net/psl1234554321/article/details/106166637