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:
- first: iterator pointing to the first element in the range.
- last: iterator pointing to the past last element in the range.
- comp: predicate function that accepts two arguments and returns true if the two arguments are in order and false otherwise.
Return Value: It returns nothing.
Example:
CPP
// C++ program to demonstrate stable sort() in STL
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
stable_sort(arr, arr + n);
cout << "Array after sorting using "
"stable_sort is : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
OutputArray after sorting using stable_sort is :
0 1 2 3 4 5 6 7 8 9
How to Sort in Descending Order using stable_sort()?
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:
CPP
// C++ program to demonstrate descending order
// stable sort using greater<>().
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
stable_sort(arr, arr + n, greater<int>());
cout << "Array after sorting : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
OutputArray after sorting :
9 8 7 6 5 4 3 2 1 0
When to Prefer stable_sort over sort()?
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,
- Consider sorting students by marks, if two students have the same marks, we may want to keep them in the same order as they appear input. Please refer to stability in sorting algorithms for details.
- Consider we have time intervals sorted by ending time and we want to sort by start time. Also, if two start times are same, we want to keep them sorted by the end time. This is not guaranteed by sort().
CPP
// A C++ program to demonstrate STL stable_sort()
// to sort intervals according to start time.
#include <bits/stdc++.h>
using namespace std;
// An interval has start time and end time
struct Interval {
int start, end;
};
// Compares two intervals according to starting
// times.
bool compareInterval(Interval i1, Interval i2)
{
return (i1.start < i2.start);
}
int main()
{
// Given intervals are sorted according to end time
Interval arr[]
= { { 1, 3 }, { 2, 4 }, { 1, 7 }, { 2, 19 } };
int n = sizeof(arr) / sizeof(arr[0]);
// sort the intervals in increasing order of
// start time such that the start time intervals
// appear in same order as in input.
stable_sort(arr, arr + n, compareInterval);
cout << "Intervals sorted by start time : \n";
for (int i = 0; i < n; i++)
cout << "[" << arr[i].start << ", " << arr[i].end
<< "] ";
return 0;
}
OutputIntervals sorted by start time :
[1, 3] [1, 7] [2, 4] [2, 19]
Difference Between sort and stable_sort()
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)).
|
Similar Reads
sort() in C++ STL In C++, sort() is a built-in function used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++, but it only works on data structures that provide random access to its elements such as vectors and arrays.Let's take a look at an example:C++#include
4 min read
std::list::sort in C++ STL Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::sort() sort() function is used to sort the
2 min read
std::stable_partition in C++ The stable_partition( ) algorithm arranges the sequence defined by start and end such that all elements for which the predicate specified by pfn returns true come before those for which the predicate returns false. The partitioning is stable. This means that the relative ordering of the sequence is
3 min read
is_sorted() in C++ STL In C++, is_sorted() is a built-in function used to check whether the element of the given range is sorted or not in ascending order. In this article, we will learn about is_sorted() function in C++.Letâs take a quick look at a simple example that illustrates is_sorted() method:C++#include <bits/s
4 min read
std::is_sorted_until in C++ std::is_sorted_until is used to find out the first unsorted element in the range [first, last). It returns an iterator to the first unsorted element in the range, so all the elements in between first and the iterator returned are sorted.It can also be used to count the total no. of sorted elements i
3 min read
Insertion sort using C++ STL Implementation of Insertion Sort using STL functions. Pre-requisites : Insertion Sort, std::rotate, std::upper_bound, C++ Iterators. The idea is to use std::upper_bound to find an element making the array unsorted. Then we can rotate the unsorted part so that it ends up sorted. We can traverse the a
1 min read