stable_sort() in C++ STL

Last Updated : 23 Dec, 2021

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 =