#include <iostream>
#include <cmath>
#include <ctime>
#include <cassert>
#include <windows.h> //微妙级计时必须的头文件
using namespace std;
//生成测试数据
namespace MyUtil
{
//生成数组长度为n,数据范围为[rangl...rangR]的随机数组
int *generateRandomArray(int n, int rangel, int rangeR)
{
assert(n > 0 && rangel <= rangeR);
int *arr = new int[n];
srand((unsigned int)time(NULL));
for (int i = 0; i < n; ++i)
{
arr[i] = rand() % (rangeR - rangel + 1) + rangel;
}
return arr;
}
//生成数组长度为n有序数组
int *generateOrderedArray(int n)
{
assert(n > 0);
int *arr = new int[n];
for (int i = 0; i < n; ++i)
{
arr[i] = i;
}
return arr;
}
} // namespace MyUtil
//快速排序算法
class MySort
{
public:
//传入的数据区间为[left...right],内部处理的数据区间为[left...right]
void static quickSort(int nums[], int left, int right)
{
if (left < right)
{
//从数组中随机选择一个数据作为基准
int baseindex = rand() % (right - left) + left;
int low = left;
int high = right;
//将选中的基准数据放到最右端
swap(nums[baseindex], nums[right]);
while (left < right)
{
//从左向右找到比基准小的数据则停止,此时right指向该数据
while (left < right && nums[left] <= nums[high])
{
++left;
}
//从右向左找到比基准大的数据则停止,此时left指向该数据
while (left < right && nums[right] >= nums[high])
{
--right;
}
//将两个数据交换位置
if (left < right)
swap(nums[left], nums[right]);
}
//将基准数据放到中间分隔位置
swap(nums[left], nums[high]);
quickSort(nums, low, left - 1);
quickSort(nums, left + 1, high);
}
}
};
int main(void)
{
//程序运行时间
double run_time = 0;
//以下测试,每次测试计算的时间精确到微秒
for (int i = 10; i <= 20; i++)
{
//计时所需的相关变量
LARGE_INTEGER start_time; //开始时间
LARGE_INTEGER end_time; //结束时间
double dqFreq; //计时器频率
LARGE_INTEGER freq; //计时器频率
QueryPerformanceFrequency(&freq);
dqFreq = (double)freq.QuadPart;
//快速排序运行时间测试
int n = pow(2, i);
int *arr = MyUtil::generateRandomArray(n, 0, 100);
QueryPerformanceCounter(&start_time); //计时开始
MySort::quickSort(arr, 0, n - 1);
QueryPerformanceCounter(&end_time); //计时结束
run_time = (end_time.QuadPart - start_time.QuadPart) / dqFreq; //计时时间计算
cout << "data size 2^" << i << "=" << n << "\t";
cout << "time cost:" << run_time << endl;
}
cout << "----------------------------------------------" << endl;
//以下测试,每次测试计算的时间精确到毫秒
for (int i = 10; i <= 20; i++)
{
int n = pow(2, i);
int *arr = MyUtil::generateRandomArray(n, 0, 100);
clock_t startTime = clock();
MySort::quickSort(arr, 0, n - 1);
clock_t endTime = clock();
run_time = double(endTime - startTime) / CLOCKS_PER_SEC;
cout << "data size 2^" << i << "=" << n << "\t";
cout << "time cost:" << run_time << endl;
}
system("pause");
return 0;
}
C/C++快速排序运行时间测试,精确到微秒
猜你喜欢
转载自blog.csdn.net/weixin_42042288/article/details/109678666
今日推荐
周排行