sortingheapsortstable-sort

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!


Solution

  • 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.