Stable N Inplace Algos
Stable N Inplace Algos
An in-place algorithm is an algorithm that does not need an extra space and produces an
output in the same memory that contains the data by transforming the input ‘in-place’.
However, a small constant extra space used for variables is allowed.
In-place means that the algorithm does not use extra space for manipulating the input but may
require a small though non-constant extra space for its operation. Usually, this space is O(log
n), though sometimes anything in O(n) (Smaller than linear) is allowed.
Not In-Place : Merge Sort. Note that merge sort requires O(n) extra space.
Stability is mainly important when we have key value pairs with duplicate keys possible (like
people names as keys and their details as values). And we wish to sort these objects by keys.
What is it?
A sorting algorithm is said to be stable if two objects with equal keys appear in the same
order in sorted output as they appear in the input array to be sorted.
i < j and Ai = Aj (2 values are the same but at different positions in the array)
implies π(i) < π(j)
where π is the sorting permutation (sorting moves A[i] to position π[i] )
Informally, stability means that equivalent elements retain their relative positions, after
sorting.
Compiled by: CSD, SPC [for M.Sc Part – I students only] 2020
Sort, Count Sort and Binary Tree Sort.
Comparison based stable sorts such as Merge Sort and Insertion Sort, maintain stability
Some sorts such as Radix Sort depend on another sort, with the only requirement that the
other sort should be stable.
One of the main difference between quicksort and mergesort is that the quicksort is unstable
but merge sort is a stable sorting algorithm.
Now, there is two possible solution for the two pairs where the key is the same i.e. (4,5) and
(4,3) as shown below:
The sorting algorithm which will produce the first output will be known as stable sorting
algorithm because the original order of equal keys are maintained, you can see that (4, 5)
comes before (4,3) in the sorted order, which was the original order i.e. in the given input, (4,
5) comes before (4, 3).
On the other hand, the algorithm which produces second output will know as an unstable
sorting algorithm because the order of objects with the same key is not maintained in the
sorted order. You can see that in the second output, the (4, 3) comes before (4, 5) which was
not the case in the original input.
Remember, Collections.sort() method from Java Collection framework uses iterative merge
sort which is a stable algorithm. It also does far fewer comparison than NLog(N) in case
input array is partially sorted.
Compiled by: CSD, SPC [for M.Sc Part – I students only] 2020
Count Sort n = 8
A
12 56 34 89 22 43 9 16
C count array
6 1 3 0 4 2 7 5
Descending order sort
89, 56, 43, 34, 22, 16, 12, 9 = Sorted array
In a day
12 (25000), 100(5000), 90(1000), 12 (20000),
Compiled by: CSD, SPC [for M.Sc Part – I students only] 2020