快速选择算法如下:
template<class Type>
void quickSelect(vector<Type>& array,int k,int left,int right)
{
//尾递归
/*
if(left<right){
if(10<=right-left){
int breakPoint=randomPartition(array,left,right);
if(breakPoint==k-1)
return;
else if(breakPoint<k-1)
quickSelect(array,k,breakPoint+1,right);
else
quickSelect(array,k,left,breakPoint-1);
}
else
insertionSort(array,left,right);
}
*/
//没有尾递归情况
while(left<right){
if(10<=right-left){
int breakPoint=randomPartition(array,left,right);
if(breakPoint==k-1)
break;
else if(breakPoint<k-1)
left=breakPoint+1;
else
right=breakPoint-1;
}
else{
insertionSort(array,left,right);
break;
}
}
}
template<class Type>
const Type& quickSelect(vector<Type>& array,int k)
{
quickSelect(array,k,0,array.size()-1);
return array[k-1];
}