其实就是在求第k小元素的基础上就第n-k+1小元素,也可以自己去改动条件,但我懒,嘿嘿
import java.util.Random;
import java.util.Scanner;
public class find_kk {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
int n,k,r;
n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
r=sc.nextInt();
k=n-r+1;
int p=quickSelect(a,0,n-1,k);
System.out.println(p);
}
}
private static int quickSelect(int[] a, int s, int t, int k) {
// TODO Auto-generated method stub
if(s==t) return a[s];
/*int u=ran(s,t);
swap(a,u,s);//随机选基准,下标还是从0 开始,只是把a[0]的值交换了*/
int i=partition(a,s,t);
//if(i==k) return a[i];
int j=i-s+1;//基准前包括基准的个数,从第1小到第j小元素
if(j>=k) {return quickSelect(a,s,i,k);}
else {return quickSelect(a,i+1,t,k-j);}
}
private static int partition(int[] a, int p, int q) {
// TODO Auto-generated method stub
int w=ran(p,q);
swap(a,p,w);
int x=a[p];
int i=p;
for(int j=p+1;j<=q;j++) {
if(a[j]<x) {
i++;
swap(a,i,j);
}
}swap(a,i,p);
return i;
}
private static int ran(int a, int b) {
// TODO Auto-generated method stub
Random ran=new Random();
int u=ran.nextInt(b-a+1)+a;
return u;
}
private static void swap(int[] a, int i, int j) {
// TODO Auto-generated method stub
int t=a[i];
a[i]=a[j];
a[j]=t;
}
}