0
点赞
收藏
分享

微信扫一扫

【算法】测试C++标准库中sort算法的平均运行时间(C++源码)


【算法】测试C++标准库中sort算法的平均运行时间(C++源码)

  • ​​一、声明​​
  • ​​二、使用​​
  • ​​三、统计​​
  • ​​四、重复​​
  • ​​五、封装​​
  • ​​六、源代码(C++)​​

一、声明

声明包含n=100000个整数的vector对象;

二、使用

使用rand()函数为vector中的元素随机赋值,要求每一个元素X的取值范围: 1<=X<=100000;

三、统计

使用sort()函数对上述随机数组进行排序并统计运行时间;

四、重复

重复上述①—③过程100次,然后计算并在屏幕打印sort()排序的平均运行时间;

五、封装

六、源代码(C++)

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<ctime>
#include<iomanip>
#include<cstdlib>

using namespace std;

int main( )
{
int j=100;
double sum=0;
for(int a=0 ; a<j ; a++)
{
srand(time(NULL));
int n = 100000;
vector<int>vec(n);
for(int i = 0 ; i < n; i++)
{
vec[i] = rand() % 101 * 1000;
}
clock_t start_time = clock();
sort(vec.begin(),vec.end());
clock_t elpased_time = clock()-start_time;
cout<<fixed<<setprecision(6);
cout<<"Time elapsed:"<<double(elpased_time)/CLOCKS_PER_SEC<<"second."<<endl;
sum=sum+double(elpased_time)/CLOCKS_PER_SEC;
}
cout<<double(sum)/100<<endl;
getchar();
return 0;
}


举报

相关推荐

0 条评论