一般选择算法看起来要比找最小值这样的简单问题更难,但有期望为线性时间的选择算法,期望运行时间为O(n)。
#include<iostream>
#include<ctime>
using namespace std;
template<class T> int partition(T *a,int first,int end) //实现了对子数组A[p..r]的原址重排
{
int x = a[end-1];
int i = first-1;
for(int j=first;j<=end-1;++j)
{
if(a[j-1] <= x)
{
++i;
swap(a[i-1],a[j-1]);
}
}
swap(a[i],a[end-1]);
return i+1;
}
template<class T>int randomizedPartition(T *a,int first,int end)
{
srand((unsigned)time(NULL));
int i = rand()%(end-first)+first;
swap(a[i],a[end-1]);
return partition(a,first,end);
}
template<class T>T randomizedSelect(T *a,int first,int end,int i) //返回数组A[first,end]中第i小的元素
{
if(first == end)
return a[first-1];
int q = randomizedPartition(a,first,end);
int k = q-first+1;
if(i==k) // the pivot value is the answer
retur