利用了快排的劃分,以及前面說的那種計數的方法。ide
1+1/2+1/4+...=2*nspa
#include<cstdio> //1+1/2+1/4+1/8+1/16+...=2*n const int MAXN=1007; void swap(int *x,int *y){ int tmp=*x; *x=*y; *y=tmp; } int a[MAXN]; int the_kth(int l,int r,int K){//L到R區間中第K大的數 if(K>=r-l+1)return -1; int i=l,j=r; while(i!=j){ while(a[j]>=a[l]&&i<j)j--; while(a[i]<=a[l]&&i<j)i++; swap(&a[i],&a[j]); } swap(&a[i],&a[l]); if(K==i-l+1)return a[i]; else if(K>i-l+1)return the_kth(i+1,r,K-(i-l+1)); else return the_kth(l,i-1,K); } int main(){ int N,K;scanf("%d%d",&N,&K); for(int i=1;i<=N;++i)scanf("%d",&a[i]); printf("%d",the_kth(1,N,K)); return 0; }