C++算法导论第九章O(n)期望选择序列第i小的数字

时间:2022-11-22 15:33:36

#include<iostream>
#include<vector>
#include<algorithm>
#include<time.h>
using namespace std;
int randomized_partition(vector<int>& vec, int le, int ri)
{
if (le == ri)
{
return le;
}
srand(time(NULL));
int _rand = le + rand() % (ri - le);
int X = vec[_rand]; //基准数
int i = le - 1, j = le;
swap(vec[_rand], vec[ri]);
while (j < ri)
{
if (vec[j] < X)
{
++i;
swap(vec[i], vec[j]);
}
++j;
}
swap(vec[i + 1], vec[j]);
return i + 1;
} int randomized_select(vector<int>& vec, int le, int ri, int i)
//选择[le,ri]中第i小的元素,O(n)时间期望,i不是索引值
{
if (le == ri)
{
return vec[le];
}
int mi = randomized_partition(vec, le, ri);
int interval = mi - le + 1;
if (i < interval)
{
return randomized_select(vec, le, mi - 1, i);
}
else
{
if (i == interval)
{
return vec[mi];
}
else
{
return randomized_select(vec, mi + 1, ri, i - interval);
}
}
} int main()
{
srand(time(NULL));
vector<int>vec(100);
for (int i = 0; i < 100; ++i)
{
vec[i] = rand() % 100;
}
cout << randomized_select(vec, 0, 99, 6) << endl;
sort(vec.begin(), vec.end());
for (int i = 0; i < 100; ++i)
{
cout << vec[i] << " ";
}
system("pause");
}