![]() |
VOOZH | about |
stable_sort() is used to sort the elements in the range [first, last) in ascending order. It is like std::sort, but stable_sort() keeps the relative order of elements with equivalent values. It comes under the <algorithm> header file.
Syntax:
template< class RandomIterator> void stable_sort( RandomIterator first, RandomIterator last );
or
template< class RandomIterator, class Compare> void stable_sort( RandomIterator first, RandomIterator last, Compare comp );
Parameters:
Return Value: It returns nothing.
Example:
Array after sorting using stable_sort is : 0 1 2 3 4 5 6 7 8 9
Like sort(), stable_sort() takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass “greater()” function to sort in decreasing order. This function does comparison in a way that puts greater element before.
Syntax:
// arr is the array and n is the size stable_sort(arr, arr + n, greater<int>());
Example:
Array after sorting : 9 8 7 6 5 4 3 2 1 0
Sometime we want to make sure that order of equal elements is same in sorted array as it was in original array. This can be useful if these values have associated other fields. For example,
Intervals sorted by start time : [1, 3] [1, 7] [2, 4] [2, 19]
Key | sort() | stable_sort() |
|---|---|---|
| Implementation | sort() function usually uses Introsort. 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. |
| Time Complexity | It is O(n*log(n)). |
It is O(n*log^2(n)). If additional memory linearly proportional to length is not available. If its available then O(n*log(n)). |