Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't heapsort stable?

I'm trying to understand why heapsort isn't stable. I've googled this, but haven't found a good, intuitive explanation.

I understand the importance of stable sorting - it allows us to sort based on more than one key, which can be very beneficial (i.e., do multiple sortings, each based on a different key. Since every sort will preserve the relative order of elements, previous sortings can add up to give a final list of elements sorted by multiple criteria). However, why wouldn't heapsort preserve this as well?

Thanks for your help!

like image 955
JMS Avatar asked Oct 12 '13 17:10

JMS


People also ask

Is heapsort stable sorting algorithm or not?

Heapsort is an in-place algorithm, but it is not a stable sort. Heapsort was invented by J. W. J. Williams in 1964.

Is heapsort stable or can it degrade as QuickSort does?

Heapsort is not stable because operations on the heap can change the relative order of equal items. When sorting (in ascending order) heapsort first peaks the largest element and put it in the last of the list.

Why Selection Sort is unstable?

Selection sort works by finding the minimum element and then inserting it in its correct position by swapping with the element which is in the position of this minimum element. This is what makes it unstable.

Why is heapsort so slow?

Sorting requires a large number of comparisons, and branching on modern CPUs can be expensive. We could end our experiment here. Heapsort is almost three times slower because it performs more than four times more instructions than quicksort. Hardware utilization for both sorting algorithms is similar (and low).


2 Answers

Heap sort unstable example

Consider array 21 20a 20b 12 11 8 7 (already in max-heap format)

here 20a = 20b just to differentiate the order we represent them as 20a and 20b

While heapsort first 21 is removed and placed in the last index then 20a is removed and placed in last but one index and 20b in the last but two index so after heap sort the array looks like

7 8 11 12 20b 20a 21.

It does not preserve the order of elements and hence can't be stable

like image 81
KD157 Avatar answered Sep 29 '22 10:09

KD157


The final sequence of the results from heapsort comes from removing items from the created heap in purely size order (based on the key field).

Any information about the ordering of the items in the original sequence was lost during the heap creation stage, which came first.

like image 29
Baldrick Avatar answered Sep 29 '22 11:09

Baldrick