利用快排的partition,在线性时间内,选择出第i大的数
template<typename Comparable>
int qPartition(vector<Comparable> &vec,int p,int r)
{
uniform_int_distribution<unsigned> u(p,r);
default_random_engine e(32676);
int pos=u(e);
std::swap(vec[pos],vec[r]);
int key=vec[r];
int i=p-1;
for(int j=p;j<r;j++)
if(vec[j]<key)
std::swap(vec[++i],vec[j]);
std::swap(vec[++i],vec[r]);
return i;
}
template<typename Comparable>
Comparable randomSelect(vector<Comparable> &vec,int p,int r,int i)
{
if(p==r)
return vec[p];
int q=qPartition(vec,p,r);
int k=q-p+1;
if(i==k)
return vec[k];
else
{
if(i<k)
return randomSelect(vec,p,q-1,i);
else
return randomSelect(vec,q+1,r,i-k);
}
}
int main()
{
vector<int> vec{1,9,8,5,7,12,3,5,6};
//qSort(vec,0,vec.size());
cout<<randomSelect(vec,0,vec.size()-1,3)<<endl;
}
本文介绍了一种基于快速排序的partition过程实现的随机选择算法,该算法可以在O(n)的时间复杂度内找到未排序数组中第i小的元素。通过随机选择pivot并进行分区,递归地缩小搜索范围直至找到目标元素。

6154

被折叠的 条评论
为什么被折叠?



