Top K问题
Q:找出一堆不重复数据中的最小或最大的几个数
解决方法:利用快速排序
代码:
#include<iostream>
using namespace std;
int n=8;
int partition(int p[],int low,int height){
int key=p[low];
while(low<height){
while(low<height&&p[height]>=key){
height--;
}
p[low]=p[height];
while(low<height&&p[low]<key){
low++;
}
p[height]=p[low];
}
p[low]=key;
return low;
}
void Qsort(int p[],int low,int height,int k){
int res=partition(p,low,height);
if((height-res-1)>k){
cout<<height-res-1<<"\t"<<k<<endl;
Qsort(p,res+1,height,k);
}
else if((height-res-1)<k){
cout<<height-res-1<<"\t"<<k<<endl;
Qsort(p,0,res-1,k);
}
else return;
}
int main(){
int arr[n]={2,3,6,1,9,4,5,7};
Qsort(arr,0,n,3);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
}