辅助
#include<time.h>
#include<iostream>
using namespace std;
void show(int a[], int length) {
for (int i = 1; i <= length; i++) {
cout << a[i] << " ";
}
cout << endl;
}
算法重点
//2.折半插入法
//需要经过[log2i]+1次比较,时间复杂度o(n^2),移动次数与直接插入算法差不多,比较次数较少
/*
特点:稳定排序,只能顺序结构,初始记录无序,n比较大
1.设待排序的记录保存在数组r[1,n]中,r[1]有序序列
2.循环(n-1)次,每次使用折半插入法,查找r[i]在已排好序的序列中的位置,直接插入,最后得到表长为n的序列
*/
void BInsertSort(int a[], int length) {
int changeTime = 0, compareTime = 0;
for (int i = 2; i <= length; i++) {
a[0] = a[i];//哨兵保存数值
changeTime++;
int low = 1, high = i - 1;//设置区间
while (low <= high) {
int meidan = (low + high) / 2;//折半
if (a[0] < a[meidan]) {
high = meidan - 1;//插入点在左区域
}
else low = meidan + 1;//插入点在右区域
compareTime++;
}
for (int j = i - 1; j >= high + 1; --j) {//记录后移
a[j + 1] = a[j]; changeTime++;
}
a[high + 1] = a[0]; changeTime++;
printf("Thr %2d time sort:\t",(i-1));
show(a, length);
}
cout << "Key word ComareTime2=" << compareTime << endl;
cout << "Key word ChangeTime2=" << changeTime << endl;
}
测试
int main() {
int *a = new int[17];
int length = 16;
srand(unsigned(time(NULL)));
for (int i = 1; i <= 16; i++) {
a[i]=rand()% 90 + 10;
}
cout << "============ ==" << endl;
cout << " 折半插入排序: " << endl;
cout << "== ============" << endl;
cout << "before sort:" << ends;
for (int i = 1; i <= 16; i++) {
cout<<a[i]<<" ";
}
cout << endl;
BInsertSort(a, length);
cout << "after sort:" << ends;
for (int i = 1; i <= 16; i++) {
cout << a[i] << " ";
}
cout << endl;
delete a;
a = NULL;
}