Qsort求静态的第K大

Who is in the middle

#include<iostream>
#include<cmath>
#include<cstdlib>
#include<utility>
using namespace std;
const int maxN=2e6+10;
int n,a[maxN],k;

int find(int l,int r,int k)
{
	if(l==r)
		return a[l];
	int t=a[(l+r)/2];
	int i=l,j=r;
	while(i<=j)
	{
		while(a[i]<t)i++;
		while(a[j]>t)j--;
		if(i<=j){
			swap(a[i],a[j]);
			i++;
			j--;
		}
	}
	if(k<=j-l+1)
		return find(l,j,k);
	else if(k>i-l)
		return find(i,r,k-(i-l));
	else 
		return t; 
}

int main()
{
	cin>>n;
	k=(1+n)/2;
	for(int i=1;i<=n;++i)
		cin>>a[i];

	cout<<find(1,n,k)<<endl;
	return 0;
} 

  

posted @ 2020-10-04 21:09  我微笑不代表我快乐  阅读(155)  评论(0编辑  收藏  举报