How to find K smallest values using quick sort

匆匆过客 提交于 2019-12-11 15:24:51

问题


The problem is simple if I sort all the values and pick the fist K values. But it wastes too much time because maybe the smallest K values has been sorted before the whole array is sorted. I think the way to solve this problem is to add a flag in the code, but I can not figure out how to put the flag to judge whether the smallest k values has been sort.


回答1:


You can use random selection algorithm to solve this problem with O(n) time. In the end, just return sub-array from 0 to k.




回答2:


I think the problem can be solved by finding the kth smallest value. Suppose the signature of the function partition in quicksort is int partition(int* array, int start, int end), here is pseudocode which illustrate the basic idea:

int select(int[] a, int start, int end, int k)
{
    j = partition(a,start,end);

    if( k == j)
        return a[j];
    if( k < j )
        select(a,start,j-1,k);
    if( k > j )
        select(a,j+1,end,k-j);
}

index = select(a, 0, length_of_a, k);

Then a[0...index] is the first k smallest values in array a. You can further sort a[0...index] if you want them sorted.



来源:https://stackoverflow.com/questions/13716821/how-to-find-k-smallest-values-using-quick-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!