C++ Algorithm stable_sort()

C++ Algorithm stable_sort() function is used to sort the elements in the range [first, last) into ascending order like sort but keeps the order of equivalent elements.

The elements are compared using operator < for the first version, and comp for the second version.

Syntax

Parameter

first: A bidirectional iterator pointing to the first element in the range to be sorted.

last: A bidirectional iterator pointing to the past last element in the range to be sorted.

comp: A user defined binary predicate function that accepts two arguments and returns true if the two arguments are in order and false otherwise. It follows the strict weak ordering to order the elements.

Return value

None

Complexity

The run time complexity depends on the amount of available memory.

If enough extra memory is available, then the complexity is linear in the distance between first and last. Performs up to N*log2 (N) element comparisons where N = last - first.

If no extra memory is available then the complexity is polylinear in the distance between first and last. Performs up to N*log22 (N) element comparisons where N = last - first.

Data races

The object in the range [first, last) are modified.

Exceptions

This function throws an exception if any of element comparisons, the element swaps or an operation on iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of stable_sort():

Output:

Before sorting: 3 1 4 2 5 
After sorting:  1 2 3 4 5

Example 2

Let's see another simple example:

Output:

Age : Name 
-----------
23 : Bob
58 : Robin
60 : Devid

Example 3

Let's see another simple example:

Output:

Stable Sort by name
Name  	Sec	Group
-------------------------
Aman	3	B
Anjali	3	A
Bob	4	C
Chinu  	3	A
Deep 	4	B
Faizal 	3	A
Nikita 	1	A
Rohit 	2	A

Stable Sort by section
Name  	Sec	Group
-------------------------
Nikita 	1	A
Rohit 	2	A
Aman	3	B
Anjali	3	A
Chinu  	3	A
Faizal 	3	A
Bob	4	C
Deep 	4	B

Example 4

Let's see another simple example:

Output:

Original vector v1 = ( 0 2 4 6 8 10 0 2 4 6 8 10 )
Sorted vector v1 = ( 0 0 2 2 4 4 6 6 8 8 10 10 )
Resorted (greater) vector v1 = ( 10 10 8 8 6 6 4 4 2 2 0 0 )
Resorted (UDgreater) vector v1 = ( 10 10 8 8 6 6 4 4 2 2 0 0 )

Next TopicC++ Algorithm




Latest Courses