Top K and Quick Selection

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Top k Largest Numbers

Quick Sort(快排)

AX7: Quick and easy debugging

scikit-learn:3. Model selection and evaluation

Best Practices for QML and Qt Quick

ISL - Ch.6 Linear Model Selection and Regularization