#include <iostream>
#include <stdlib.h>
using namespace std;
void Qsort(int a[],int low,int high)
{
if(low >= high) return;
int first = low;
int last = high;
int key = a[first];
while(first < last)
{
while(first < last && a[last] >= key) --last;
a[first] = a[last];
while(first < last && a[first] <= key) ++first;
a[last] = a[first];
}
a[first] = key;
Qsort(a, low, first - 1);
Qsort(a, first + 1, high);
}
int main(int argc, char **argv)
{
//命令行参数数量判断
if (argc == 0) {
cout << "Usage: quicksort N\n";
return 0;
}
//命令行第2个参数转换为长整数
long N = atoi(argv[1]);
//随机化数
srand( time(0) );
//动态分配内存
int *a;
a = new int[N]; //C++
for(long i = 0; i < N; i++)
a[i] = rand();
//计时
clock_t t1 = clock();
Qsort(a, 0, N-1);/*这里原文第三个参数要减1否则内存泄露*/
clock_t t2 = clock();
cout << (double)(t2 - t1) / CLOCKS_PER_SEC << "秒" << endl;
/*//输出
for(int i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
cout<<a[i]<<"";
}
*/
//释放申请的内存
delete []a; //C++
return 0;
}
跨平台C++毫秒计时——以Quick Sort算法为例子
最新推荐文章于 2024-09-22 18:04:56 发布