Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What algorithms do popular C++ compilers use for std::sort and std::stable_sort?

What algorithms do popular C++ compilers use for std::sort and std::stable_sort? I know the standard only gives certain performance requirements, but I'd like to know which algorithms popular implementations use in practice.

The answer would be more useful if it cited references for each implementation.

like image 480
static_rtti Avatar asked Jan 27 '13 13:01

static_rtti


People also ask

What algorithm does std :: Stable_sort use?

Stable Sort The std::stable_sort in terms of function signature is no different from std::sort, but the difference is that std::stable_sort uses Merge Sort algorithm and has time complexity of O(N log(N)²) where N = std::distance(first, last) applications of the comparation function.

What algorithm does sort use in C++?

The algorithm used by sort() is IntroSort. Introsort being a hybrid sorting algorithm uses three sorting algorithm to minimize the running time, Quicksort, Heapsort and Insertion Sort. Simply putting, it is the best sorting algorithm around.

What is the difference between sort and Stable_sort algorithms?

Therefore, sort() may preserve the physical order of semantically equivalent values but can't be guaranteed. stable_sort() function usually uses mergesort. Therefore, stable_sort() preserve the physical order of semantically equivalent values and its guaranteed. It is O(n*log(n)).

Which is the fastest sorting algorithm in C++?

The fastest sorting algorithm would be no-op-sort: It's preconditions include a sorted array as input.


1 Answers

First of all: the compilers do not provide any implementation of std::sort. Whilst traditionally each compiler comes prepackaged with a Standard Library implementation (which heavily relies on compilers' built-ins) you could in theory swap one implementation for another. One very good example is that Clang compiles both libstdc++ (traditionally packaged with gcc) and libc++ (brand new).

Now that this is out of the way...

std::sort has traditionally been implemented as an intro-sort. From a high-level point of view it means a relatively standard quick-sort implementation (with some median probing to avoid a O(n2) worst case) coupled with an insertion sort routine for small inputs. libc++ implementation however is slightly different and closer to TimSort: it detects already sorted sequences in the inputs and avoid sorting them again, leading to an O(n) behavior on fully sorted input. It also uses optimized sorting networks for small inputs.

std::stable_sort on the other hand is more complicated by nature. This can be extrapolated from the very wording of the Standard: the complexity is O(n log n) if sufficient additional memory can be allocated (hinting at a merge-sort), but degenerates to O(n log2 n) if not.

like image 107
Matthieu M. Avatar answered Sep 21 '22 06:09

Matthieu M.