您的位置:首页 > 编程语言 > C语言/C++

C++计算运行时间和随机数的插入排序

2017-03-15 17:08 232 查看
#include<iostream>

#include<cstdlib>

#include <ctime>

using namespace std;

void InsertionSort (int a[],int len)

{
if (a==NULL||len<=1)
{
return ;
}
for(int j=1;j<len;j++)
{

int temp=a[j];
int p=j;
while(p>0&&a[p-1]>temp)
{
a[p]=a[p-1];
p--;

}
a[p]=temp;
}

}

void InsertionTwoSort (int a[],int len)

{
if (a==NULL||len<=1)
{
return ;
}

for(int j=1;j<len;j++)
{

int temp=a[j];
//可以考虑二分插入
int start=0,end=j;
while(start<end)
{
int mid=start+(end-start)/2;
if (a[mid]<temp)
{
start=mid+1;
}
else
end=mid;

}
int p=j;
while(p>end)
{
a[p]=a[p-1];
p--;

}
a[p]=temp;
}

}

void SortRunTime(int a[],int length)

{
clock_t start,end;
start=clock();
InsertionTwoSort(a,length);
end=clock();
cout<<" Insert RunTime : "<<(double)(end-start)/CLOCKS_PER_SEC;

}

int rand(int p,int q)

{
int size=q-p+1;
return p+rand()%size;

}

int main()

{
int a[100000];
int num=100000;
for (int i=0;i<num;i++)
{
a[i]=rand(0,200000);
}
SortRunTime(a,num);

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: