![]() |
VOOZH | about |
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.
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.
Output:
Array after sorting : 9 8 7 6 5 4 3 2 1 0
Time Complexity: O(n logn)
Auxiliary Space: O(1)