要求:
随机函数产生10000 个随机数并统计每一种排序所花费的时间。
直接插入法:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include <windows.h>
#include<algorithm>
using namespace std;
#define ll long long
#define maxn 10000
ll length=maxn;
ll a[maxn+10];
void Insort(){
int i,j;
for(i=2;i<=length;i++){
if(a[i]<a[i-1]){
a[0]=a[i];
a[i]=a[i-1];
for(j=i-2;a[0]<a[j];j--)
a[j+1]=a[j];
a[j+1]=a[0];
}
}
}
int main(){
ll x;
DWORD start, stop;//记录时间
unsigned int t = 0;
start = GetTickCount();//时间开始
for(x=1;x<=length;x++){//随机生成10000个数:
a[x]=rand();
}
Insort();
for(x=1;x<=length;x++){
printf("%d ",a[x]);
}
printf("\n");
stop = GetTickCount();//时间结束
printf("time: %lld ms\n", stop - start);
return 0;
}
二分插入
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include <windows.h>
#include<algorithm>
using namespace std;
#define ll long long
#define maxn 10000
ll length=maxn;
ll a[maxn+10];
void Insort(){
int i,j,m,low,high;
for(i=2;i<=length;i++){
a[0]=a[i];
low=1; high=i-1;
while(low<=high){
m=(low+high)/2;
if(a[0]<a[m]) high=m-1;
else low=m+1;
}
for(j=i-1;j>=high+1;--j) a[j+1]=a[j];
a[high+1]=a[0];
}
}
int main(){
ll x;
DWORD start, stop;//记录时间
unsigned int t = 0;
start = GetTickCount();//时间开始
for(x=1;x<=length;x++){//随机生成10000个数:
a[x]=rand();
}
Insort();
for(x=1;x<=length;x++){
printf("%d ",a[x]);
}
printf("\n");
stop = GetTickCount();//时间结束
printf("time: %lld ms\n", stop - start);
return 0;
}