What is the difference between std::sort and std::stable_sort?

Yes, it’s as you said, and this is not a concept unique to C++.

Stable sorts preserve the physical order of semantically equivalent values.


std::sort:

The order of equal elements is not guaranteed to be preserved.
Complexity: O(N·log(N)), where N = std::distance(first, last) comparisons

std::stable_sort:

The order of equal elements is guaranteed to be preserved.
Complexity: O(N·log^2(N)), where N = std::distance(first, last) applications of cmp. If additional memory is available, then the complexity is O(N·log(N)).

The implication is that std::stable_sort cannot be performed quite as efficiently in terms of execution time, unless “additional memory is available” in which case it is not being performed as efficiently in terms of memory consumption.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)