部分排序数组,所以最后n个元素被排序? [英] Partially sorting array so last n elements are sorted?

查看:117
本文介绍了部分排序数组,所以最后n个元素被排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法对数据数组执行部分排序,以便最后n个元素排序?好的我的意思是使用标准库,不实现我自己的排序函数(这是我现在正在做的)。
示例输出(使用较少的比较器):

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.

这基本上是对std :: partial_sort函数的反转,它对左(第一)元素进行排序。

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

推荐答案

使用反向迭代器使用 std :: partial_sort

例如:

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

这篇关于部分排序数组,所以最后n个元素被排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆