線性時間選出一個數組中第i大的數

利用快排的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;
}

發佈了93 篇原創文章 · 獲贊 9 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章