简化版的快速排序,因为快排其实就是两个哨兵相互移动,然后递归来进行排序,如果两个哨兵相遇的地点其实就是第K大的话,那我们无需再进行递归,直接返回此值,就行;同理只需要知道第K大的值位于哨兵相遇左边还是右边,再针对性做递归即可。

import java.util.*;

public class Solution {
    public int findKth(int[] a, int n, int K) {
        // write code here
        return returnK(a,0,a.length - 1, a.length - K);
    }
    public int returnK(int[] a,int s,int e,int K){
        while(s >= e){
            return a[s];
        }
        int l = s;
        int r = e;
        int stand = a[s];
        while(l < r){
            while(l < r && a[r] >= stand){
                r--;
            }
            while(l < r && a[l] <= stand){
                l++;
            }
            int temp = a[l];
            a[l] = a[r];
            a[r] = temp;
        }
        a[s] = a[l];
        a[l] = stand;
        if(l == K) return stand;
        else if(l < K){
            return returnK(a,l + 1,e,K);
        }else{
            return  returnK(a,s,l - 1,K);
        }
    }
}