獲得第k小元素

分治,關鍵是用到快拍的時候的partation函數

#include<iostream>
#include<hash_map>
#include<string>
#include<iterator>
#include<algorithm>

using namespace std;
const int maxn=100;
int tab[maxn];
template<class T>
int random_partition(T* tab,int p,int q)
{
	if(p==q)return p;
	//select one pos and then swap this postion element with the first
	int pos=rand()%(q-p)+p;
	swap(tab[p],tab[pos]);
	int left=p+1,right=q;
	while(left<=right){
		while(tab[left]<=tab[p]&&left<=q)++left;
		while(tab[right]>=tab[p]&&right>=p+1)--right;
		if(left<right)swap(tab[left],tab[right]);				
	}
	swap(tab[p],tab[right]);
	return right;
}

int selectKthMin(int* tab,int p,int q,int k)
{
	if(p==q)return tab[p];
	int r=random_partition<int>(tab,p,q);
	int pos=r-p+1;
	if(pos==k)return tab[r];
	if(pos>k)return selectKthMin(tab,p,r-1,k);
	return selectKthMin(tab,r+1,q,k-pos);
}

int main()
{ 
	int n=8;
	int tab[]={0,10,2,13,4,5,6,27};
	for(int i=1;i<=7;i++)
	cout<<selectKthMin(tab,1,7,i)<<endl;
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章