1

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.

Now in std::sort in the standard library, returning false when two elements are equal is a must. Hence, is it safe to say that the sorting algorithm used is unstable?

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
harsh
  • 83
  • 8
  • [What's the difference between “STL” and “C++ Standard Library”?](https://stackoverflow.com/questions/5205491/whats-the-difference-between-stl-and-c-standard-library) – François Andrieux Dec 08 '20 at 15:15
  • As far as I know, nobody has discovered or invented an O(n*log(n)) in-place stable sorting algorithm yet. – molbdnilo Dec 08 '20 at 15:23
  • @molbdnilo I think [this](https://en.wikipedia.org/wiki/Merge_sort#Variants) mentions some. And is `std::sort` guaranteed in-place, or why did you say that? – superb rain Dec 08 '20 at 21:00

4 Answers4

4

Now in the sort function in STL, returning false when two elements are equal is a must. 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; if you require a stable sort, use std::stable_sort.

But the string weak ordering requirement is unrelated, and is the same for both std::sort and std::stable_sort.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

std::sort() is not guaranteed to be stable, and in practice it will never be implemented as stable since stable sort is slower. If you need stable sort, use std::stable_sort().

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
Eugene
  • 6,194
  • 1
  • 20
  • 31
2

returning false when two elements are equal is a must.

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. 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).

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
-2

Check the C++ reference at http://www.cplusplus.com/reference/algorithm/sort/ which clearly indicates it to be not stable

TKA
  • 183
  • 2
  • 4