/*
利用快排的特点(假设默认升序排序),每一次快排操作都能确定一个数在排序结果中的最终固定位置,即该位置 pos 上的数为 N - pos 大的数,且之后的数即为前 N - pos 大的数,故此方法即可求第k大的数 也可求前k大的数。
设取第k大的数,即index = k;
若 pos < index; 就继续快排右侧的数据;
若 pos > index; 就继续快排左侧的数据;
若 pos == index; 即要求的结果。
*/
#include<iostream>
using namespace std;
const int maxn = 1e8+9;
int a[maxn];
int qsort(int l,int r){
int temp = a[l];
while(l<r){
while(l<r&&a[r]<temp) r--;
a[l] = a[r];
while(l<r&&a[l]>temp) l++;
a[r] = a[l];
}
a[l] = temp;
return l;
}
int main(){
int n; cin >> n;
int l = 1,r = n,index; cin >> index;
for(int i=1; i<=n; i++){
cin >> a[i];
}
int pos = qsort(l,r);
while(pos!=index){
if(pos>index)
r = pos-1;
else
l = pos+1;
/*这里对pos有个特殊的操作,是更新每次的区间,
即“基准数”已经满足要求了 */
pos = qsort(l,r);
}
cout << a[index] << endl;
return 0;
}
第k大问题
最新推荐文章于 2022-07-08 10:24:50 发布