c++ - 部分排序 : nth elements having preseved order

标签 c++ nth-element partial-sort

任务是对具有重复项 s.t. 的 vector 进行部分排序。如果对 vector 进行排序,则中位数(第 n 个元素)位于应有的位置。所有较小的元素都应该在左边,所有较大的元素在右边。值与中位数相同的所有元素都必须按原始顺序 - 但只有这些元素而不是其余元素。

你会如何解决这个问题?

我最初的解决方案:

  1. 使用 std::nth_element() 寻找中值元素
  2. 遍历 vector ,只对与中值相同的元素的索引进行排序。我将如何有效地做到这一点?

最佳答案

使用分区或稳定分区(以保留原始顺序)。

class Predicate{
    int median_value;
    public:
    Predicate(int med) : median_value(med) {}
    bool operator()(int x){
    return x < median_value;
    }
};

int main(){

vector<int> v{ 10, 20, 30, 10, 30};

int median = 20;

cout << "median  = " << median << endl;

stable_partition(v.begin(), v.end(), Predicate(median));

for ( auto i : v)
    cout << i << " ";
}

关于c++ - 部分排序 : nth elements having preseved order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30391288/

相关文章:

c++ - 使用 ifstream 时出现语法错误

c++ - C++ 的平台独立性。检测与编译

c++ - nth_element 实现复杂性

sorting - 如何在 Spark DataFrame 上应用部分排序?

算法: Divide and Conquer (Application of Quick Sort?!)

c++ - Qt - 如何拦截应用程序的关闭事件(如果有的话)

c++ - nth_element 是如何实现的?

c++ - std::nth_element 提供了错误的值

c# - 是否有等同于 C++ std::partial_sort 的 C#?

c++ - char_traits<char16_t>::int_type 的大小不够大吗?