基于快排:每次划分之后返回该次划分的基准索引,比较索引和K的大小,K大,则往右继续划分,K小,则往右划分。直到求解为止。该算法不会把快排执行完毕,也就是说数组中还有没有排好序的一些元素。

public class Solution {
    public int findKth(int[] a, int n, int K) {
         quicksort(a,0,n-1,K);
        return a[K-1];
    }
    public void quicksort(int[] a, int low,int high , int K){
        if(low<high){
            int mid = partion(a,low,high);
            if(mid==K-1)return;
            else if(mid<K-1){
                 quicksort(a,mid+1,high,K);
            }
            else 
                quicksort(a,low,mid-1,K);
        }
    }
    public int partion(int [] a,int low,int high){
        int pivot = a[low];
        while(low<high){
            while(low<high&&a[high]<=pivot)--high;
            a[low] = a[high];
            while(low<high&&a[low]>=pivot)++low;
            a[high] = a[low];
            a[low] = pivot;
        }
        return low;
    }
}