Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::sort change the relative order of equal elements?

Tags:

c++

stl

Does the standard guarantee that order of equal elements will not change (eh, forgot the term for that) by using std::sort or do I need to consider an alternative solution to achieve this goal?

like image 430
vehomzzz Avatar asked Oct 27 '09 18:10

vehomzzz


2 Answers

std::sort is not guaranteed to be stable (the term you were trying to think of). As you'd guess, std::stable_sort is guaranteed to be stable. std::stable_sort also provides a guarantee on worst-case complexity, which std::sort does not. std::sort is typically faster on average though.

like image 181
Jerry Coffin Avatar answered Nov 06 '22 06:11

Jerry Coffin


From C++ reference: here

Elements that would compare equal to each other are not guaranteed to keep their original relative order.

You might want stable_sort, but note that it's not as fast (in average)

like image 39
Matthieu M. Avatar answered Nov 06 '22 06:11

Matthieu M.