Home »
Algorithms
Stability in sorting
Here, we are going to learn about the sorting and stability of the sorting.
Submitted by Himanshu Singh Bisht, on November 09, 2018
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.
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.
Unstable Algorithm
Name | Section |
Himanshu | A |
Aakash | A |
Ravi | A |
Raju | B |
Deeksha | B |
Ayush | B |
Samiksha | C |
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.
TOP Interview Coding Problems/Challenges