Finding nth largest element inplace

时间:2016-04-07 10:44:51

标签: c++ algorithm c++11 stl nth-element

I need to find nth largest element in an array and currently I'm doing it the following way:

std::vector<double> buffer(sequence); // sequence is const std::vector<double>
std::nth_element(buffer.begin(), buffer.begin() + idx, buffer.end(), std::greater<double>());
nth_element = buffer[idx];

But is there any way to find the n-th largest element in an array without using an external buffer?

2 个答案:

答案 0 :(得分:9)

使用std::partial_sort_copy可以避免在不修改原始范围的情况下复制整个缓冲区。只需将部分排序的范围复制到较小的n缓冲区中,然后取最后一个元素。

如果您可以修改原始缓冲区,则只需使用std::nth_element即可。

答案 1 :(得分:0)

您可以使用快速排序中使用的分区功能查找第n个最大元素。

分区函数将原始数组分为两部分。第一部分将小于A [i],第二部分将大于A [i],分区将返回i。如果i等于n然后返回A [i]。如果我小于n,则对第二部分进行分区。如果我大于n,则对第一部分进行分区。

它不会花费你额外的缓冲,平均时间成本是O(n)。