Home »
Algorithms
What is stability in sorting?
In this tutorial, we will learn about the sorting and stability of the sorting.
By Himanshu Singh Bisht Last updated : August 12, 2023
What is sorting?
It means to arrange data elements in increasing or decreasing order. There are many algorithms to do so like mergesort, quicksort, counting sort etc but there are pros and cons of each algorithm.
Stability of sorting
One way to judge the algorithm is the stability of sorting. Stability means that the relative position of elements remain same after sorting if an equal key element exists.
To demonstrate it suppose a table having name column and section column.
Name | Section |
Himanshu | A |
Raju | B |
Aakash | A |
Samiksha | C |
Ayush | B |
Ravi | A |
Deeksha | B |
Consider a scenario of sorting on basis of the name of student and section also. Now the first sort according to the name of the student Table will be like:
Name | Section |
Aakash | A |
Ayush | B |
Deeksha | B |
Himanshu | A |
Raju | B |
Ravi | A |
Samiksha | C |
Now sort according to the section, there will be two output based on the algorithm is stable or not. Due to unstable algorithm now the name has become unsorted so either it will be sorted in name order or section order.
Example of unstable algorithm
Name | Section |
Himanshu | A |
Aakash | A |
Ravi | A |
Raju | B |
Deeksha | B |
Ayush | B |
Samiksha | C |
Example of stable algorithm
Name | Section |
Aakash | A |
Himanshu | A |
Ravi | A |
Ayush | B |
Deeksha | B |
Raju | B |
Samiksha | C |
As observed with unstable sort task cannot be achieved because one sorting is disordering previous sorting that is why stable sort will be preferred in the database.