Partially sorting array so last n elements are sorted?

可紊 提交于 2020-01-03 08:40:23

问题


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.


回答1:


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 << ' ';



回答2:


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();


来源:https://stackoverflow.com/questions/14348602/partially-sorting-array-so-last-n-elements-are-sorted

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