Heap sort
Heap sort
Important points:
• Heap sort is an in-place algorithm.
• Its typical implementation is not stable, but can be made stable (See this)
• Typically 2-3 times slower than well-implemented QuickSort. The reason for slowness is a lack of
locality of reference.
Advantages of heapsort:
• Efficiency – The time required to perform Heap sort increases logarithmically while other
algorithms may grow exponentially slower as the number of items to sort increases. This sorting
algorithm is very efficient.
• Memory Usage – Memory usage is minimal because apart from what is necessary to hold the
initial list of items to be sorted, it needs no additional memory space to work
• Simplicity – It is simpler to understand than other equally efficient sorting algorithms because it
does not use advanced computer science concepts such as recursion.
Disadvantages and applications of Heap
Sort:
Disadvantages of Heap Sort:
• Costly: Heap sort is costly.
• Unstable: Heap sort is unstable. It might rearrange the relative order.
• Efficient: Heap Sort are not very efficient when working with highly complex data.
Applications of HeapSort:
• Heapsort is mainly used in hybrid algorithms like the IntroSort.
• Sort a nearly sorted (or K sorted) array
• k largest(or smallest) elements in an array
What is meant by Heapify?
Algorithm for Heapify:
Since heapify uses recursion, it can be difficult to grasp. So let's first think about how you would
heapify a tree with just three elements.
How to "heapify" a tree
Now let's think of another scenario in which there is more than one level.
The top element isn't a max-heap but all the sub-trees are max-heaps.
How to heapify root
element when its
subtrees are already
max heaps