C++实现先生成n个随机数,使用随机选择算法,分析算法的运行时间随个数n的变化情况。
时间: 2024-03-02 14:53:08 浏览: 22
下面是C++实现先生成n个随机数,使用随机选择算法并分析算法的运行时间随着个数n的变化情况:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// 交换两个元素的值
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// 随机选择算法
int random_select(int arr[], int left, int right, int k)
{
if (left == right)
return arr[left];
int pivotIndex = left + rand() % (right - left + 1); // 随机选择一个元素作为枢纽元素
pivotIndex = partition(arr, left, right, pivotIndex); // 划分后枢纽元素所在位置
if (k == pivotIndex)
return arr[k];
else if (k < pivotIndex)
return random_select(arr, left, pivotIndex - 1, k);
else
return random_select(arr, pivotIndex + 1, right, k);
}
// 快速排序中的划分函数
int partition(int arr[], int left, int right, int pivotIndex)
{
int pivotValue = arr[pivotIndex];
swap(&arr[pivotIndex], &arr[right]); // 把枢纽元素移到末尾
int storeIndex = left;
for (int i = left; i < right; i++)
{
if (arr[i] < pivotValue)
{
swap(&arr[i], &arr[storeIndex]);
storeIndex++;
}
}
swap(&arr[storeIndex], &arr[right]); // 把枢纽元素移到正确的位置
return storeIndex;
}
int main()
{
srand(time(NULL)); // 初始化随机数种子
int n;
cout << "请输入随机数的个数:";
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
arr[i] = rand() % 100; // 生成0~99之间的随机整数
int k;
cout << "请输入要查找第几小的数:";
cin >> k;
clock_t start, end;
start = clock();
int result = random_select(arr, 0, n - 1, k - 1);
end = clock();
cout << "第" << k << "小的数是:" << result << endl;
cout << "算法的运行时间为:" << (double)(end - start) / CLOCKS_PER_SEC << "秒" << endl;
return 0;
}
```
该程序采用随机选择算法,先生成n个随机数,然后查找第k小的数。我们可以通过改变n的大小,来分析算法的运行时间随着n的变化情况。
需要注意的是,本程序中的时间复杂度为O(n),但是随机选择算法的期望时间复杂度为O(n),因此本程序中的运行时间与n的大小有关,但是并不是线性关系。
我们可以通过多次运行程序,取平均值来得到更加精确的运行时间。