Search code examples
c++sortingstandard-library

Partially sorting array so last n elements are sorted?


Is there a way to perform a partial sort on an array of data so that the last n elements are sorted? By good I mean using the standard library, not implementing my own sort function (this is what I'm doing right now). Example output (using less comparator):

2 1 4 || 5 6 8 10

Elements after || are all greater than elements than elements before ||, but only elements to the right of || (indices closer to the end of the array) are guaranteed to be sorted.

This is basically a reversal of the std::partial_sort function which sorts the left (first) elements.


Solution

  • Use std::partial_sort with reverse iterators.

    For example:

    int x[20];
    std::iota(std::begin(x), std::end(x), 0);
    std::random_shuffle(std::begin(x), std::end(x));
    
    std::reverse_iterator<int*> b(std::end(x)),
                                e(std::begin(x));
    std::partial_sort(b, b+10, e, std::greater<int>());
    for (auto i : x)
        std::cout << i << ' ';