Heap Sort
Heap Sort
There are two types of heap data structures and they are as follows...
Max Heap
Min Heap
Min Heap
A Min Heap Binary Tree is a Binary Tree where the root node has the minimum key in the tree.
The above definition holds true for all sub-trees in the tree. This is called the Min Heap property.
Almost every node other than the last two layers must have two children. That is, this is almost a
complete binary tree, with the exception of the last 2 layers.
The below tree is an example of a min heap binary tree since the above two properties hold
Max Heap
A max heap is a complete binary tree in which the value of a node is greater than or equal to the values of
its children. Max Heap data structure is useful for sorting data using heap sort.
In a Min-Heap the key present at the In a Max-Heap the key present at the
root node must be less than or equal to root node must be greater than or equal
among the keys present at all of its to among the keys present at all of its
1. children. children.
1. Transform the array into a binary tree by inserting each element as a node in a
breadth-first manner.
2. Convert the binary tree into a max heap, ensuring that all parent nodes are
greater than or equal to their child nodes.
3. Swap the root node — the largest element — with the last element in the heap.
4. Call the heapify() function to restore the max heap property.
5. Repeat steps 3 and 4 until the heap is sorted, and exclude the last element
from the heap on each iteration.
6. After each swap and heapify() call, ensure that the max heap property is
satisfied.
Complexity of the Heap Sort Algorithm
To sort an unsorted list with 'n' number of elements, following are the complexities...