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!
Heapsort is an in-place algorithm, but it is not a stable sort. Heapsort was invented by J. W. J. Williams in 1964.
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.
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.
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).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With