# 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

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.

Learn PCB Designing: PCB DESIGNING TUTORIAL