首页 > 代码库 > Top K and Quick Selection

Top K and Quick Selection

The common solutions for top k problem are heap (priority queue) and quick selection. Using heap is very straight-forward, while quick selection with partition is more complicated and I didnot find any satisfying code online, so document as following.

References: 

Explanation (written by python): https://www.youtube.com/watch?v=SXXpkdruLfc

Quicksort template: http://www.jiuzhang.com/solutions/quick-sort/ 

 

 

public static int partition(int[] a, int start, int end) {
        int pivot = start;
        int i = start+1;
        int j = end;
        
        while (i <= j) {
            while (i <= j && a[i] <= a[pivot]) {
                i++;
            }
            
            while (i <= j  && a[j] > a[pivot]) {
                j--;
            }
            
            if (i <= j) {
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
        int temp = a[pivot];
        a[pivot] = a[j];
        a[j] = temp;
        return j;
    }
    public static int quick(int[] a, int start, int end, int k ){
        if (start == end)
            return a[start];
        
        if (start < end) {
            int pivot = partition(a, start, end);
            
            int length = pivot - start + 1;
            if (length == k)
                return a[pivot];
            if (length > k) {
                return quick(a,start,pivot-1,k);
            } else {
                return quick(a, pivot+1, end, k-length);
            }
            
        }
        return -1;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a = {72,5,57,88,60,5,38,73,48,85};
        //int[] a = {1,1,1,1,1,1};
        int index = 4;
        System.out.println("Before sorting " + Arrays.toString(a));
        System.out.println("My answer: " + quick(a, 0, a.length-1,index));
        Arrays.sort(a);
        System.out.println("After sorting " + Arrays.toString(a));
        System.out.println("Correct answer: " + a[index-1]);
    }

 

Top K and Quick Selection