Stable vs Unstable Sorting Algorithms

Stable vs Unstable Sorting Algorithms

Kinda important

·

2 min read

After learning the fundamentals of the basic sorting algorithms, I went straight to the interview questions to get a gist of what is being asked as part of my study routine. There I came across this question "What is the difference between a stable and unstable sorting algorithm?". I had no clue about it and that's when the research began.

It's not as complex as it might sound (it doesn't even sound complicated in my opinion).

So, here's my simplest explanation of it.

Before that, tell me what would be the output after sorting this array.

{5,4,2,3,1} //unsorted

The answer is pretty simple, the sorted array will be.

{1,2,3,4,5} //sorted

Now, what do you think will be the output of this array after applying a sorting algorithm of your choosing.

{2,2,3,5,4,1} //unsorted

For a better understanding, imagine the first "2" be red in colour and the second "2" be blue in colour.

Coming back to sorting, how do you decide which "2" comes first in the sorted array? The blue or the red one?

If the sorting algorithm maintains the relative order of items in the array i.e red comes before blue, it is called a stable sorting algorithm.

If it doesn't, It is an unstable sorting algorithm.

Merge Sort, Insertion Sort, Bubble Sort, and Binary Tree Sort are examples of stable algorithms. QuickSort, Heap Sort, and Selection Sort, on the other hand, are unstable sorting algorithms.

I hope you found this information useful. Just so I know it was, leave a comment or a reaction.