部分排序数组,最后n个元素排序

Partially sorting array so last n elements are sorted?

本文关键字:排序 最后 元素 数组      更新时间:2023-10-16

是否有一种方法对数据数组执行部分排序,以便对最后n个元素进行排序?我说的好是指使用标准库,而不是实现我自己的排序函数(这就是我现在正在做的)。示例输出(使用less comparator):

2 1 4 || 5 6 8 10

||之后的元素都大于||之前的元素,但只有||右边的元素(靠近数组末尾的索引)才保证被排序。

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

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

另一种可能性是使用std::nth_element对集合进行分区,然后使用std::sort对您关心的分区进行排序,而不是使用反向迭代器partial_sort和std::greater进行比较:

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

在c++20中使用范围和视图是非常简单的。

数组的例子:

//DATA
int arrayOfInts[8] = { 82,80,81,86,83,85,84,88 };
//SORT LAST 5 ELEMENTS. SO DROP FIRST 3.
std::ranges::sort(std::views::drop(arrayOfInts, 3));
//PRINT ARRAY -- 82  80  81 || 83  84  85  86  88
for (auto i : arrayOfInts)
    std::cout << i << "  ";
向量的例子:

//DATA
std::vector<int> vecOfInts = { 82,80,81,86,83,85,84,88 };
//SORT LAST 5 ELEMENTS. SO DROP FIRST 3.
std::ranges::sort(std::views::drop(vecOfInts, 3));
//PRINT VECTOR -- 82  80  81  || 83  84  85  86  88
for (auto i : vecOfInts)
    std::cout << i << "  ";