I have a list of random integers. I’m wondering which algorithm is used by the list::sort() method. E.g. in the following code:
list<int> mylist;
// ..insert a million values
mylist.sort();
EDIT: See also this more specific question.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The standard doesn’t require a particular algorithm, only that it must be stable, and that it complete the sort using approximately N lg N comparisons. That allows, for example, a merge-sort or a linked-list version of a quick sort (contrary to popular belief, quick sort isn’t necessarily unstable, even though the most common implementation for arrays is).
With that proviso, the short answer is that in most current standard libraries,
std::sortis implemented as a intro-sort (introspective sort), which is basically a Quicksort that keeps track of its recursion depth, and will switch to a Heapsort (usually slower but guaranteed O(n log n) complexity) if the Quicksort is using too deep of recursion. Introsort was invented relatively recently though (late 1990’s). Older standard libraries typically used a Quicksort instead.stable_sortexists because for sorting array-like containers, most of the fastest sorting algorithms are unstable, so the standard includes bothstd::sort(fast but not necessarily stable) andstd::stable_sort(stable but often somewhat slower).Both of those, however, normally expect random-access iterators, and will work poorly (if at all) with something like a linked list. To get decent performance for linked lists, the standard includes
list::sort. For a linked list, however, there’s not really any such trade-off — it’s pretty easy to implement a merge-sort that’s both stable and (about) as fast as anything else. As such, they just required onesortmember function that’s required to be stable.