这个是在上一篇插入排序的基础上的改进。在查找第i个元素的正确位置的过程中,使用折半查找加速。数据量大的情况下效率应该有比较显著的提升。
//折半插入排序
//lovesunmoonlight
//2017.3.24
#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
#define MAX 10
typedef struct{
int key; //关键字
double data; //数据
}node;
typedef struct{
node r[MAX+1]; //r[0]的位置设置为哨兵
int len;
}List;
void binaryInsertSort(List& s)
{
for(int i=2;i<s.len;i++)
{
s.r[0]=s.r[i]; //保存到哨兵
int low=1;
int high=i-1;
int mid=low+(high-low)/2;
while(low<=high)
{
if(s.r[0].key<s.r[mid].key)
{
high=mid-1;
}
else
{
low=mid+1;
}
mid=low+(high-low)/2;
}
int j;
for(j=i-1;j>=high+1;j--)
{
s.r[j+1]=s.r[j];
}
s.r[high+1]=s.r[0];
}
}
void output(const List& s)
{
cout<<"Key Data"<<endl;
for(int i=1;i<s.len;i++)
cout<<s.r[i].key<<" "<<s.r[i].data<<endl;
cout<<endl;
}
int main()
{
List s;
//初始化表
s.len=MAX+1;
s.r[0].key=0;
s.r[0].data=-1;
for(int i=1;i<s.len;i++)
{
s.r[i].data=rand()%100;
s.r[i].key=rand()%50;
}
cout<<"Initialized: "<<endl;
output(s);
binaryInsertSort(s);
cout<<"After binaryInsertSort: "<<endl;
output(s);
return 0;
}
结果: