Description

Stable_sort is much like sort: it sorts the elements in
[first, last) into ascending order, meaning that if i and j are
any two valid iterators in [first, last) such that i precedes j,
then *j is not less than *i. Stable_sort differs from
sort in two ways. First, stable_sort uses an algorithm that
has different run-time complexity than sort. Second, as the
name suggests, stable_sort is stable: it preserves the relative
ordering of equivalent elements. That is, if x and y are elements
in [first, last) such that x precedes y, and if the two
elements are equivalent (neither x < y nor y < x)
then a postcondition of stable_sort is that x still precedes y.
[1]

The two versions of stable_sort differ in how they define whether one
element is less than another. The first version compares
objects using operator<, and the second compares objects using
a function objectcomp.

Preconditions

[first, last) is a valid range.

Complexity

Stable_sort is an adaptive algorithm: it attempts to
allocate a temporary memory buffer, and its run-time complexity depends
on how much memory is available. Worst-case behavior (if no auxiliary memory
is available) is N (log N)^2 comparisons, where N is last -
first, and best case
(if a large enough auxiliary memory buffer is available)
is N (log N). [2]

Example

Sort a sequence of characters, ignoring their case. Note that the
relative order of characters that differ only by case is preserved.

Notes

[1]
Note that two elements may be equivalent without being equal.
One standard example is sorting a sequence of names by last name: if
two people have the same last name but different first names, then
they are equivalent but not equal. This is why stable_sort is
sometimes useful: if you are sorting a sequence of records that have
several different fields, then you may want to sort it by one field
without completely destroying the ordering that you previously
obtained from sorting it by a different field. You might, for
example, sort by first name and then do a stable sort by last name.