Category: algorithms | Component type: function |
template <class RandomAccessIterator> void stable_sort(RandomAccessIterator first, RandomAccessIterator last); template <class RandomAccessIterator, class StrictWeakOrdering> void stable_sort(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp);
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 object comp.
inline bool lt_nocase(char c1, char c2) { return tolower(c1) < tolower(c2); } int main() { char A[] = "fdBeACFDbEac"; const int N = sizeof(A) - 1; stable_sort(A, A+N, lt_nocase); printf("%s\n", A); // The printed result is ""AaBbCcdDeEfF". }
[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.
[2] Stable_sort uses the merge sort algorithm; see section 5.2.4 of Knuth. (D. E. Knuth, The Art of Computer Programming. Volume 3: Sorting and Searching. Addison-Wesley, 1975.)