Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is stability in sorting algorithms and why is it important?

I'm very curious, why stability is or is not important in sorting algorithms?

like image 449
DarthVader Avatar asked Oct 05 '09 00:10

DarthVader


People also ask

What is meant by stability of sorting algorithm?

Stability in Sorting Algorithms The stability of a sorting algorithm is concerned with how the algorithm treats equal (or repeated) elements. Stable sorting algorithms preserve the relative order of equal elements, while unstable sorting algorithms don't.

What is the importance of sorting algorithms?

A sorting algorithm will put items in a list into an order, such as alphabetical or numerical order. For example, a list of customer names could be sorted into alphabetical order by surname, or a list of people could be put into numerical order by age.

What is stable sorting algorithm with example?

Some examples of stable algorithms are Merge Sort, Insertion Sort, Bubble Sort and Binary Tree Sort. While, QuickSort, Heap Sort, and Selection sort are the unstable sorting algorithm. If you remember, Collections. sort() method from Java Collection framework uses iterative merge sort which is a stable algorithm.


1 Answers

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. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort, etc. And some sorting algorithms are not, like Heap Sort, Quick Sort, etc.

Background: a "stable" sorting algorithm keeps the items with the same sorting key in order. Suppose we have a list of 5-letter words:

peach straw apple spork 

If we sort the list by just the first letter of each word then a stable-sort would produce:

apple peach straw spork 

In an unstable sort algorithm, straw or spork may be interchanged, but in a stable one, they stay in the same relative positions (that is, since straw appears before spork in the input, it also appears before spork in the output).

We could sort the list of words using this algorithm: stable sorting by column 5, then 4, then 3, then 2, then 1. In the end, it will be correctly sorted. Convince yourself of that. (by the way, that algorithm is called radix sort)

Now to answer your question, suppose we have a list of first and last names. We are asked to sort "by last name, then by first". We could first sort (stable or unstable) by the first name, then stable sort by the last name. After these sorts, the list is primarily sorted by the last name. However, where last names are the same, the first names are sorted.

You can't stack unstable sorts in the same fashion.

like image 193
Joey Adams Avatar answered Sep 20 '22 19:09

Joey Adams