营销型网站的建设软文,烟台住房和城乡建设厅网站,wordpress 挖矿脚本,介绍一个做美食的网站1、简述#xff1a;
折半插入排序#xff08;binary insertion sort#xff09;是对插入排序算法的一种改进#xff0c;由于排序算法过程中#xff0c;就是不断的依次将元素插入前面已排好序的序列中。由于前半部分为已排好序的数列#xff0c;这样我们不用按顺序依次寻…
1、简述
折半插入排序binary insertion sort是对插入排序算法的一种改进由于排序算法过程中就是不断的依次将元素插入前面已排好序的序列中。由于前半部分为已排好序的数列这样我们不用按顺序依次寻找插入点可以采用折半查找的方法来加快寻找插入点的速度。 实现步骤
定义已知列表arr从第二个元素开始i1arr[temp] arr[i] arr[low] 表示首元素arr[high]表示末元素中间值arr[mid] arr[ (lowhigh)/2];比较temp和mid 的元素大小 当temp mid则选择low到mid-1的位置作为新插入区域即[low, highmid-1]否则选择mid1到high的位置作为新插入区域即[lowmid1, high]循环直到lowhigh不成立移动元素将[low, i)位置的元素向后移动把temp的元素插到low的位置。 2、复杂度
时间复杂度O(n²)比直接插入算法明显减少了关键字之间比较的次数因此速度比直接插入排序算法快但记录移动的次数没有变
空间复杂度O(1) 3、稳定性稳定排序 4、例子 C代码
#include iostream
using namespace std;#define LEN 8 // 有LEN个元素要排void BInsertSort(int arr[], int length)
{for(int i 1; i length; i){int temp arr[i];int low 0;int high i - 1;while(low high){ // 在arr[low..high]中折半查找有序插入的位置int mid (low high) / 2; // 折半if(temp arr[mid]){ // 关键字相同时使low m 1到高半区保证稳定性high mid - 1; // 插入点在低半区}else{low mid 1; // 插入点在高半区}}for(int j i; j low 1; j--){arr[j] arr[j - 1];}arr[low] temp;coutii的排序结果;for (int a 0;a length;a) {cout arr[a] ;}coutendl;}
}
int main(void)
{int arr[LEN] {45, 98, 66, 90, 88, 78, 25, 45};BInsertSort(arr, 8);return 0;
}
输出结果
i1的排序结果45 98 66 90 88 78 25 45
i2的排序结果45 66 98 90 88 78 25 45
i3的排序结果45 66 90 98 88 78 25 45
i4的排序结果45 66 88 90 98 78 25 45
i5的排序结果45 66 78 88 90 98 25 45
i6的排序结果25 45 66 78 88 90 98 45
i7的排序结果25 45 45 66 78 88 90 98 参考折半插入排序_百度百科