简体   繁体   English

`std::sort` function 不稳定吗?

[英]Is the `std::sort` function unstable?

Just wanted to confirm if what I am thinking is right or wrong.只是想确认我的想法是对还是错。 According to the definition:根据定义:

A sorting algorithm is said to be stable if two objects with equal or same keys appear in the same order in sorted output as they appear in the input array to be sorted.如果具有相同或相同键的两个对象以相同的顺序出现在已排序的 output 中,则称该排序算法是稳定的,因为它们出现在要排序的输入数组中。

Now in std::sort in the standard library, returning false when two elements are equal is a must.现在在标准库的std::sort中,当两个元素相等时返回 false 是必须的。 Hence, is it safe to say that the sorting algorithm used is unstable?因此,可以肯定地说所使用的排序算法是不稳定的吗?

Now in the sort function in STL, returning false when two elements are equal is a must.现在在 STL 中的排序 function 中,当两个元素相等时返回 false 是必须的。 Hence, is it safe to say that the sorting algorithm used is unstable?因此,可以肯定地说所使用的排序算法是不稳定的吗?

No, that's completely unrelated.不,这完全无关。

As a matter of fact, std::sort isn't guaranteed to be stable;事实上, std::sort不能保证是稳定的。 if you require a stable sort, use std::stable_sort .如果您需要稳定的排序,请使用std::stable_sort

But the string weak ordering requirement is unrelated, and is the same for both std::sort and std::stable_sort .但是字符串弱排序要求是不相关的,对于std::sortstd::stable_sort都是相同的。

std::sort() is not guaranteed to be stable, and in practice it will never be implemented as stable since stable sort is slower. std::sort()不能保证是稳定的,实际上它永远不会被实现为稳定的,因为稳定排序较慢。 If you need stable sort, use std::stable_sort() .如果您需要稳定排序,请使用std::stable_sort()

returning false when two elements are equal is a must.当两个元素相等时返回 false 是必须的。

That doesn't make the difference between a stable and a non-stable sorting algorithm.这并没有区分稳定和不稳定的排序算法。

The two major standard sorting algorithms are std::sort and std::stable_sort .两种主要的标准排序算法是std::sortstd::stable_sort The first is not guaranteed to be stable, the latter is.第一个不保证是稳定的,后者是。 Both require < or the comparator that is used as predicate to implement a strict weak ordering (which implies a < a is false for any a ).两者都需要<或用作谓词的比较器来实现严格的弱排序(这意味着a < a对于任何a都是false的)。

Check the C++ reference at http://www.cplusplus.com/reference/algorithm/sort/ which clearly indicates it to be not stable检查http://www.cplusplus.com/reference/algorithm/sort/上的 C++ 参考,这清楚地表明它不稳定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM