2

We just learned about Heap sort in class today, and I am very confused as how it's considered so efficient - IE having O(nlogn).

  • It's not memory efficient, since you have to build a heap representing the entire array and modify it constantly.
  • It's not computationally efficient, since you have to find the max every time and bring it to the root.

I may just not understand heaps very well, but it all seems like a very roundabout way of doing Selection sort, yet somehow it's considered significantly more efficient... why is that the case?

Dankraft
  • 23
  • 4

1 Answers1

2

It's not memory efficient, since you have to build a heap representing the entire array

The "central trick" which Heap Sort is based on (without which it would probably not be relevant) is that the array can be heapified in-place (this can be done in linear time), and the heap then stays there in the start of the array the whole time, shrinking in lock step with the growing range of sorted items at the end of the array. The whole algorithm can proceed with no allocation and no recursion: O(1) memory overhead.

It's not computationally efficient, since you have to find the max every time and bring it to the root.

There is no search. Any item can be dropped into the root, and then "bubbled down" to restore the heap property. The most obvious choice is the last item in the heap, which is trivial to remove (it doesn't leave a "hole" in the heap, it only decreases the size by 1). It's at the same place in the array where you're going to place the value which was the old root, so this item had better get out of the way anyway.

harold
  • 53,069
  • 5
  • 75
  • 140