#include<bits/stdc++.h>
using namespace std;
int N[10005];
typedef struct{
int key;
//int m;
}ElemType;
typedef struct{
int len;
ElemType *r;
}sq;
void CreateNum(){
srand((unsigned)time(NULL));
for(int i=1;i<=10000;i++){
N[i]=rand()%10000;
}
}
sq init(){
sq L;
L.len=10000;
L.r=new ElemType[10001];
int t=10000;
for(int i=1;i<=t;i++){
L.r[i].key=N[i];
}
return L;
}
void InsertSort(sq &L){
int j;
for(int i=2;i<=L.len;i++){
if(L.r[i].key<L.r[i-1].key){
L.r[0].key=L.r[i].key;
for(j=i-1;L.r[j].key>L.r[0].key;j--){
L.r[j+1].key=L.r[j].key;
}
L.r[j+1].key=L.r[0].key;
}
}
}
void BInsertSort(sq &L){
int j,l,r,temp;
for(int i=2;i<=L.len;i++){
temp=L.r[i].key;
l=1,r=i-1;
while(l<=r){
int m=(l+r)/2;
if(temp<L.r[m].key) r=m-1;
else l=m+1;
}
for(j=i;j>=l+1;j--) L.r[j].key=L.r[j-1].key;//L.r[j]=L.r[j-1];
L.r[l].key=temp;
}
}
void ShellSort(){
}
void show(sq L){
for(int i=1;i<=L.len;i++)
cout<<L.r[i].key<<' ';
puts("");
}
int main(){
int op;
CreateNum();//先生成一组随机数
while(1){
cout<<"请输入操作1.直接插入2.二分插入"<<endl;
cin>>op;
cout<<"更新随机数1.更新2.不更新"<<endl;//不更新保证数据相同,比较时间
int op2;
cin>>op2;
if(op2==1) CreateNum();
if(op==1){
sq L=init();//注意如果表在while外面创建,
//如不清空只能使用一次,所以可以每次使用都创建一次
double s=clock();
InsertSort(L);
double e=clock();
cout<<"时间是"<<e-s<<endl;
show(L);
}
else if(op==2){
sq L=init();
double s=clock();
//cout<<s<<endl;
BInsertSort(L);
double e=clock();
//cout<<e<<endl;
cout<<"时间是"<<e-s<<endl;
show(L);
}
else {
cout<<"敬请期待"<<endl;
system("pause");
exit(1);
}
}
return 0;
}
因篇幅问题不能全部显示,请点此查看更多更全内容