Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 328
helloworld922 Avatar asked Jan 15 '13 23:01

helloworld922


2 Answers

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 << ' ';
like image 93
Benjamin Lindley Avatar answered Nov 10 '22 22:11

Benjamin Lindley


Another possibility instead of partial_sort with reverse iterators and std::greater for the comparison would be to use std::nth_element to partition the collection, then std::sort to sort the partition you care about:

std::vector<int> data{5, 2, 1, 6, 4, 8, 10}; //  your data, shuffled

std::nth_element(data.begin(), data.begin()+2, data.end());

std::sort(data.begin()+2, data.end();
like image 40
Jerry Coffin Avatar answered Nov 10 '22 22:11

Jerry Coffin