sort2——随机数生成测试样例

来源:互联网 发布:2017年python饱和了 编辑:程序博客网 时间:2024/06/05 11:00

一、直接使用rand()函数生成:

别遗漏头文件,注意随机种子的设置方法(展示的是标准的C/C++办法)。

#include <iostream>#include <algorithm>#include <ctime>using namespace std;template<typename T>void Print_Array(T a[], int n) {for (int i = 0; i < n; ++i)cout << a[i] << "\t";cout << endl;}intmain() {//使用生成随机数方式来生成数组数据,并输出原数组数据,假设有1000个数值const int SIZE = 1000;int* arr = new int[SIZE];//首先需要设置随机种子,以C++标准实现srand(time(NULL));for (int i = 0; i < SIZE; ++i)arr[i] = rand();//赋值,rand()函数返回一个0~RAND_MAX的伪随机整数,unsigned int 类型//STL排序,默认为升序,"<=",并输出排序后数组Print_Array(arr, SIZE);sort(arr, arr + SIZE);Print_Array(arr, SIZE);//记得解除分配内存,避免发生内存泄漏问题delete[] arr;return 0;}


运行结果:





二、标准的随机数生成办法,设置随机数生成范围。实现如下:

注意assert()函数的用法。


#include <iostream>#include <algorithm>#include <ctime>#include <cassert>using namespace std;template<typename T>void Print_Array(T a[], int n) {for (int i = 0; i < n; ++i)cout << a[i] << " ";cout << endl;}intmain() {//使用生成随机数方式来生成数组数据,并输出原数组数据,假设有100个数值const int SIZE = 100;int* arr = new int[SIZE];//首先需要设置随机种子,以C++标准实现srand(time(NULL));int randL = 1, randR = 50;assert(randL <= randR);//必须保证左值不大过右值//赋值,赋一个[randL,randR]范围的伪随机整数,unsigned int 类型for (int i = 0; i < SIZE; ++i)arr[i] = rand()% (randR - randL +1) + randL;//STL排序,默认为升序,"<=",并输出排序后数组Print_Array(arr, SIZE);sort(arr, arr + SIZE);Print_Array(arr, SIZE);//记得解除分配内存,避免发生内存泄漏问题delete[] arr;return 0;}



运行结果:





三、简单的测试下 库函数排序算法 sort()  所需时间,实现如下:


#include <iostream>#include <algorithm>#include <ctime>#include <cassert>using namespace std;intmain() {//使用生成随机数方式来生成数组数据const int SIZE = 10000;int* arr = new int[SIZE];//首先需要设置随机种子,以C++标准实现srand(time(NULL));int randL = 10, randR = 20;//设置范围[left,right]闭区间assert(randL <= randR);//必须保证左值不大过右值//赋值,赋一个[randL,randR]范围的伪随机整数,unsigned int 类型for (int i = 0; i < SIZE; ++i)arr[i] = rand()% (randR - randL +1) + randL;clock_t startTime = clock();//开始时刻sort(arr, arr + SIZE);clock_t endTime = clock();//结束时刻cout <<"SIZE = "<<SIZE<<endl <<"STL_Sort : " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;//记得解除分配内存,避免发生内存泄漏问题delete[] arr;return 0;}

运行结果:

无。。。

开玩笑,只是测试了多组数据,把运行时间合并在一起做了比较而已,据说 STL的sort()时间复杂度是 O(N)log2N.




原创粉丝点击