Stable sort for descending order
Last Updated :
22 Mar, 2023
Given an array of n integers, we have to reverse sort the array elements such the equal keys are stable after sorting.
Examples:
Input : arr[] = {4, 2, 3, 2, 4}
Output : 4, 4, 3, 2, 2
Prerequisite : Stability in sorting algorithms
Method 1 (Writing our own sorting function : Bubble Sort)
We know sorting algorithms like Bubble Sort, Insertion Sort, Merge Sort, Count Sort are stable. We implement here Bubble Sort.
Explanation
First Pass
(4', 2', 3, 2", 4") -> (2', 4', 3, 4", 2") Here algorithm compares last two element and
swaps since 2" < 4".
(2', 4', 3, 4", 2") -> (2', 4', 4", 3, 2") swap since 3 < 4"
(2', 4', 4", 3, 2") -> (2', 4', 4", 3, 2")
(2', 4', 4", 3, 2") -> (4', 2', 4", 3, 2") swap since 2' < 4'.
Second Pass:
(4', 2', 4", 3, 2") -> (4', 2', 4", 3, 2")
(4', 2', 4", 3, 2") -> (4', 2', 4", 3, 2")
(4', 2', 4", 3, 2") -> (4', 4", 2', 3, 2") swap since 2' (4', 4", 2', 3, 2")
Third Pass:
(4', 4", 2', 3, 2") -> (4', 4", 2', 3, 2")
(4', 4", 2', 3, 2") -> (4', 4", 3, 2', 2") swap since 2'<3
Now, the array is in sorted order and same elements are in same order as they were in the original array.
C++
// Bubble sort implementation to sort
// elements in descending order.
#include <iostream>
#include <vector>
using namespace std;
void print(vector<int> a, int n)
{
for (int i = 0; i <= n; i++)
cout << a[i] << " ";
cout << endl;
}
// Sorts a[] in descending order using
// bubble sort.
void sort(vector<int> a, int n)
{
for (int i = n; i >= 0; i--)
for (int j = n; j > n - i; j--)
if (a[j] > a[j - 1])
swap(a[j], a[j-1]);
print(a, n);
}
// Driver code
int main()
{
int n = 7;
vector<int> a;
a.push_back(2);
a.push_back(4);
a.push_back(3);
a.push_back(2);
a.push_back(4);
a.push_back(5);
a.push_back(3);
sort(a, n - 1);
return 0;
}
Java
// Bubble sort implementation
// to sort elements in
// descending order.
import java.io.*;
import java.util.*;
class GFG
{
static void print(ArrayList<Integer> a,
int n)
{
for (int i = 0; i <= n; i++)
System.out.print(a.get(i) + " ");
System.out.println();
}
// Sorts a[] in descending
// order using bubble sort.
static void sort(ArrayList<Integer> a,
int n)
{
for (int i = n;
i >= 0; i--)
for (int j = n;
j > n - i; j--)
if (a.get(j) > a.get(j - 1))
{
int tempswap = a.get(j);
a.remove(j);
a.add(j, a.get(j - 1));
a.remove(j - 1);
a.add(j - 1, tempswap);
}
print(a, n);
}
// Driver code
public static void main(String[] args)
{
int n = 6;
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(2);
a.add(4);
a.add(3);
a.add(2);
a.add(4);
a.add(5);
a.add(3);
sort(a, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Python3
# Bubble sort implementation to sort
# elements in descending order.
def print1(a, n):
for i in range(0,n+1):
print(a[i],end=" ")
print("")
# Sorts a[] in descending order using
# bubble sort.
def sort(a, n):
for i in range(n,0,-1):
for j in range(n, n - i,-1):
if (a[j] > a[j - 1]):
a[j], a[j-1]=a[j-1], a[j]
print1(a,n)
# Driver code
n = 7
a = [2,4,3,2,4,5,3]
sort(a, n-1)
# This code is contributed
# by Smitha Dinesh Semwal
C#
// Bubble sort implementation
// to sort elements in
// descending order.
using System;
using System.Collections.Generic;
class GFG
{
static void print(List<int> a,
int n)
{
for (int i = 0; i <= n; i++)
Console.Write(a[i] + " ");
Console.WriteLine();
}
// Sorts a[] in descending
// order using bubble sort.
static void sort(List<int> a,
int n)
{
for (int i = n;
i >= 0; i--)
for (int j = n;
j > n - i; j--)
if (a[j] > a[j - 1])
{
int tempswap = a[j];
a[j] = a[j - 1];
a[j - 1] = tempswap;
}
print(a, n);
}
// Driver code
static void Main()
{
int n = 6;
List<int> a = new List<int>();
a.Add(2);
a.Add(4);
a.Add(3);
a.Add(2);
a.Add(4);
a.Add(5);
a.Add(3);
sort(a, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
<?php
// Bubble sort implementation
// to sort elements in
// descending order.
function swap(&$x, &$y)
{
$x ^= $y ^= $x ^= $y;
}
function print1($a, $n)
{
for ($i = 0; $i <= $n; $i++)
echo ($a[$i] . " ");
echo ("\n");
}
// Sorts a[] in descending
// order using bubble sort.
function sort1($a, $n)
{
for ($i = $n;
$i >= 0; $i--)
{
for ($j = $n;
$j > $n - $i; $j--)
{
if ($a[$j] > $a[$j - 1])
swap($a[$j],
$a[$j - 1]);
}
}
print1($a, $n);
}
// Driver code
$n = 6;
$a = array();
array_push($a, 2);
array_push($a, 4);
array_push($a, 3);
array_push($a, 2);
array_push($a, 4);
array_push($a, 5);
array_push($a, 3);
sort1($a, $n);
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
JavaScript
<script>
// Bubble sort implementation
// to sort elements in
// descending order.
function print(a,n)
{
for (let i = 0; i <= n; i++)
document.write(a[i] + " ");
document.write("<br>");
}
// Sorts a[] in descending
// order using bubble sort.
function sort(a,n)
{
for (let i = n;
i >= 0; i--)
for (let j = n;
j > n - i; j--)
if (a[j] > a[j-1]){
let tempswap = a[j];
a[j] = a[j - 1];
a[j - 1] = tempswap;
}
print(a, n);
}
// Driver code
let n = 6;
let a=[];
a.push(2);
a.push(4);
a.push(3);
a.push(2);
a.push(4);
a.push(5);
a.push(3);
sort(a, n);
// This code is contributed by avanitrachhadiya2155
</script>
Output:
5 4 4 3 3 2 2
Time Complexity: O(n*n)
Auxiliary Space: O(1)
Method 2 (Using library function)
We can use stable_sort to sort elements in stable manner.
C++
// C++ program to demonstrate descending order
// stable sort using greater<>().
#include <bits/stdc++.h>
using namespace std;
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;
}
Java
import java.util.*;
class GFG
{
static void reverse(int a[])
{
int i, k, n = a.length;
int t;
for (i = 0; i < n / 2; i++)
{
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
int n = arr.length;
Arrays.sort(arr);
reverse(arr);
System.out.println("Array after sorting : \n");
for (int i = 0; i < n; ++i)
{
System.out.print(arr[i] + " ");
}
}
}
// This code has been contributed by 29AjayKumar
Python 3
# Python 3 program to demonstrate
# descending order
if __name__ == "__main__":
arr = [ 1, 5, 8, 9, 6,
7, 3, 4, 2, 0 ]
n = len(arr)
arr.sort(reverse = True)
print("Array after sorting : ")
for i in range(n):
print(arr[i], end = " ")
# This code is contributed by ita_c
C#
// C# program to demonstrate descending order
using System;
class GFG
{
static void reverse(int []a)
{
int i, k, n = a.Length;
int t;
for (i = 0; i < n / 2; i++)
{
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// Driver code
public static void Main(String[] args)
{
int []arr = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
int n = arr.Length;
Array.Sort(arr);
reverse(arr);
Console.WriteLine("Array after sorting : \n");
for (int i = 0; i < n; ++i)
{
Console.Write(arr[i] + " ");
}
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// javascript program to demonstrate descending order
function reverse(a)
{
var i, k, n = a.length;
var t;
for (i = 0; i < n / 2; i++)
{
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// Driver code
var arr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ] ;
var n = arr.length;
arr.sort();
reverse(arr);
document.write("Array after sorting : " + "<br>");
for (var i = 0; i < n; ++i)
{
document.write(arr[i] + " ");
}
// This code is contributed by bunnyram19.
</script>
Output:
Array after sorting :
9 8 7 6 5 4 3 2 1 0
Time Complexity: O(n logn)
Auxiliary Space: O(1)
Similar Reads
How to Sort a Vector in Descending Order Using STL in C++? Sorting vector in descending order means arranging the elements in such a way that the first element will be largest, and second element will be second largest and so on.In C++, the simplest way to sort the vector in descending order is to by using the sort() function with a custom comparator.C++#in
3 min read
Unstable Sort meaning in DSA Unstable sorting algorithm can be defined as sorting algorithm in which the order of objects with the same values in the sorted array are not guaranteed to be the same as in the input array. Properties of Unstable Sorting Algorithm:They do not require the overhead of keeping the order of equal eleme
2 min read
Stable Selection Sort A sorting algorithm is said to be stable if two objects with equal or same keys appear in the same order in sorted output as they appear in the input array to be sorted.Any comparison based sorting algorithm which is not stable by nature can be modified to be stable by changing the key comparison op
6 min read
Sort given array to descending-lowest-ascending form Given an array arr[] of size N and an integer K, the task is to sort the array such that the first K elements of the array are in descending order and the last N - K elements of the array are in ascending order. Examples: Input: arr[]= {7, 6, 8, 9, 0, 1, 2, 2, 1, 8, 9, 6, 7}, K = 6 Output: 9 9 8 8 7
5 min read
Position of an element after stable sort Given an array of integers which may contain duplicate elements, an element of this array is given to us, we need to tell the final position of this element in the array, if a stable sort algorithm is applied. Examples : Input : arr[] = [3, 4, 3, 5, 2, 3, 4, 3, 1, 5], index = 5 Output : 4 Element in
6 min read
NavigableSet descendingSet() method in Java The descendingSet() method of NavigableSet interface in Java is used to return a reverse order view of the elements contained in this set. The descending set is backed by this set, so any changes to the set are reflected in the descending set, and vice-versa. If any of the set is modified while an i
2 min read
Stable QuickSort A sorting algorithm is said to be stable if it maintains the relative order of records in the case of equality of keys.Input : (1, 5), (3, 2) (1, 2) (5, 4) (6, 4) We need to sort key-value pairs in the increasing order of keys of first digit There are two possible solution for the two pairs where th
9 min read
Stable and Unstable Sorting Algorithms Stability is mainly essential when we have key-value pairs with duplicate keys possible (like people's names as keys and their details as values). And we wish to sort these objects by keys.What is a stable sorting algorithm? A sorting algorithm is said to be stable if two objects with equal keys app
3 min read
What is Sorting in DSA | Sorting meaning Sorting is defined as the process of arranging a collection of data elements in a specific order, usually in ascending or descending order based on a specific attribute of the data elements. Characteristics of Sorting:Time Complexity: Time complexity, a measure of how long it takes to run an algorit
3 min read
Sort a linked list that is sorted alternating ascending and descending orders? Given a Linked List. The Linked List is in alternating ascending and descending orders. Sort the list efficiently. Example: Input List: 10 -> 40 -> 53 -> 30 -> 67 -> 12 -> 89 -> NULL Output List: 10 -> 12 -> 30 -> 40 -> 53 -> 67 -> 89 -> NULL Input List: 1 -
13 min read