Fastest way to obtain the largest X numbers from a very large unsorted list?

后端 未结 3 786
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 04:51

I\'m trying to obtain the top say, 100 scores from a list of scores being generated by my program. Unfortuatly the list is huge (on the order of millions to billions) so sorting

3条回答
  •  时光说笑
    2021-02-15 05:31

    Here's the 'natural' C++ way to do this:

    std::vector v;
    // fill in v
    std::partial_sort(v.begin(), v.begin() + 100, v.end(), std::greater());
    std::sort(v.begin(), v.begin() + 100);
    

    This is linear in the number of scores.

    The algorithm used by std::sort isn't specified by the standard, but libstdc++ (used by g++) uses an "adaptive introsort", which is essentially a median-of-3 quicksort down to a certain level, followed by an insertion sort.

提交回复
热议问题