views:

502

answers:

3

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.

+14  A: 

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

Edit: As to why there's a stable_sort: for sorting array-like containers, most of the fastest sorting algorithms are unstable, so the standard includes both std::sort (fast but not necessarily stable) and std::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 one sort member function that's required to be stable.

Jerry Coffin
Why then is there a `stable_sort` in the STL ?
Matthieu M.
+3  A: 

It's completely implementation defined. The only thing the standard says about it is that it's complexity is O(n lg n), and that the sort is stable. That is, relative order of equal elements is guaranteed to not change after sorting.

std::list's sort member function is usually implemented using some form of merge sort, because merge sort is stable, and merges are really really cheap when you are working with linked lists.

Hope that helps :)

Billy ONeal
You probably mean that relative order of *equal* elements is guaranteed not to change after sorting.
meriton
That is correct :) Thanks.
Billy ONeal
+1  A: 

Though is it implementation/vendor dependent, but most implementation I know uses Introsort whose best & worst case complexity is O(nlogn).

Reference:http://en.wikipedia.org/wiki/Introsort

nthrgeek