Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an "unstable sort" considered bad

Just wondering if someone could explain why an "unstable sort" is considered bad? Basically I don't see any situations where it would really matter. Could anyone care to provide one?

like image 641
Maxim Gershkovich Avatar asked May 11 '11 03:05

Maxim Gershkovich


People also ask

Why is stable sorting important?

A stable sorting algorithm maintains the relative order of the items with equal sort keys. An unstable sorting algorithm does not. In other words, when a collection is sorted with a stable sorting algorithm, items with the same sort keys preserve their order after the collection is sorted.

What is a unstable sort?

If a sorting algorithm is said to be "unstable", this means that for any items that rank the same, the order of the tied members is not guaranteed to stay the same with successive sorts of that collection. For a 'stable' sort, the tied entries will always end up in the same order when sorted.

Which type of sorting is worst?

Selection sort It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort.

What makes a sorting algorithm unstable?

A sorting algorithm is said to be stable if it maintains the relative order of numbers/records in the case of tie i.e. if you need to sort 1 1 2 3 then if you don't change the order of those first two ones then your algorithm is stable, but if you swap them then it becomes unstable, despite the overall result or ...


1 Answers

If you have a GUI that allows people to sort on individual columns by clicking on that column, and you use a stable sort, then people who know can get a multi-column sort on columns A,B,C by clicking on columns C,B,A in that order. Because the sort is stable, when you click on B any records with equal keys under B will still be sorted by C so after clicking on B the records are sorted by B, C. Similarly, after you click on A, the records are sorted by A, B, C.

(Unfortunately, last time I tried this on some Microsoft product or other, it looked like it didn't use a stable sort, so it's not surprising this trick is not better known).

like image 98
mcdowella Avatar answered Sep 30 '22 20:09

mcdowella