Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::list<>::sort stable?

Tags:

c++

sorting

stl

I couldn't find any definitive answer to this question.

I suppose most implementation use merge sort that is stable but, is the stability a requirement or a side effect?

like image 996
Edouard A. Avatar asked Mar 04 '09 10:03

Edouard A.


People also ask

Can you use std::sort with a list?

std::sort requires random access iterators and so cannot be used with list .

Is std::list sorted?

std::list::sort. Sorts the elements in ascending order. The order of equal elements is preserved. The first version uses operator< to compare the elements, the second version uses the given comparison function comp .

What is the difference between sort and stable sort?

Stable sorting algorithms preserve the relative order of equal elements, while unstable sorting algorithms don't. In other words, stable sorting maintains the position of two equals elements relative to one another.

What does std::sort do?

std::sort() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, and (by default) sorts the iterable in ascending order. The function can also​ be used for custom sorting by passing in a comparator function that returns a boolean.


2 Answers

C++ Standard ISO/IEC 14882:2003 says:

23.2.2.4/31

Notes: Stable: the relative order of the equivalent elements is preserved. If an exception is thrown the order of the elements in the list is indeterminate.

like image 150
Paul Avatar answered Sep 30 '22 19:09

Paul


Yes, std::list<>::sort is guaranteed to be stable.

See http://www.sgi.com/tech/stl/List.html

like image 39
dalle Avatar answered Sep 30 '22 19:09

dalle