有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。 给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
利用快速排序,数组大的一半放在左边,小的一半放在右边,寻找K位置,若K=中间点的相对位置,则直接输出a[p],若K小于中间点相对位置,则在左边继续递归快排,若大于中间点相对位置,则在右边继续快排。
import java.util.*;
public class Finder {
public int findKth(int[] a, int n, int K) {
// write code here
return findKth(a,0,n-1,K);
}
public int findKth(int[] a,int low,int high,int K){//判断K的相对位置
int p = findP(a,low,high);
if(K == p-low+1)return a[p];
else if(K > p-low+1)return findKth(a,p+1,high,K-(p-low+1));
else return findKth(a,low,p-1,K);
}
public int findP(int[] a,int low,int high){//快排找中间值
int key = a[low];
while(low<high){
while(low<high && a[high] < key)high--;
a[low] = a[high];
while(low<high && a[low] > key)low++;
a[high] = a[low];
}
a[low] = key;
return low;
}
}