The heap can be built from a list in O (n logn) time, since inserting an element into the heap takes O (logn) time and n elements.
Similarly, a binary search tree can be constructed from a list in O (n logn) time, since inserting an element into a BST takes average login time and there are n elements.
Moving the heap from min-to-max takes O (n logn) time (because we have to output n elements, and each pop requires an O (logn) immersion operation). Moving a BST from min-to-max takes O (n) time (literally just a workaround).
So, it seems to me that building both structures takes equal time, but BST is faster than iteration. So why do we use "Heapsort" instead of "BSTsort"?
Edit: Thanks to Tobias and lrlreon for your answers! So, below are the points at which we use heaps instead of BST for sorting.
- Heap building can be done in O (n) time, not O (nlogn). This makes the heap construct faster than the BST construct.
- In addition, arrays can easily be converted to heaps in place, because heaps are always full binary trees. BSTs cannot be easily implemented as an array, since BSTs are not guaranteed to be complete binary trees. This means that BST requires additional allocation of O (n) space for sorting, while Heaps only requires O (1).
- All heap operations are guaranteed to be O (logn) time. BST, if they are not balanced, can have O (n) operations. Heaps are significantly easier to implement than balanced BSTs.
- If you need to change the value after creating the heap, all you have to do is apply the shell or swimming operations. Changing a value in a BST is much more conceptually complex.
source share