Heap
A heap is a complete binary tree with an additional ordering property.
A complete binary tree is one where every level is fully filled, except possibly the last
The last level is filled left to right.
This property allows easy storage in arrays.
Types
- Min heap : Every node
it's children. Root is minimum - Max heap : Every node
it's children. Root is maximum
Array representation
For every node, at index
- Left child is at
- Right child is
- Parent is at
Core operations
Insert (push)
- Insert at the end
- Fix heap property by bubbling-up (heapify-up).
Steps :
- Add element at last index
- Compare with parent
- Swap if violation of property
- Repeat
Time complexity :
Extract (pop)
- To remove root
- Replace root with last valid element (last in terms of array).
- Delete last element (now root)
- Fix heap property by heapify down
Steps:
- Swap root
- Compare new root
- Swap if violation
Time complexity :
Heapify
This refers to the process of building a heap from an unsorted array
Naive approach
Insert element one by one, while continually maintaining heap property and fixing if violated.
Time complexity :
Bottom up heapify
We assume that the last few elements are already leaf nodes. Since they have no children, they can violate no properties (note that property is only with children, not parent).
Precisely, the leaf nodes in an array of size
This means that the last non-leaf node is at index
Therefore we iterate backwards from that index and go to zero.
At each node, since we would've already processed it's children, we need only to process the current node, and fix it's property (if broken) by using heapify-down.
The advantage is that, since at each node we only work on the existing subtree, and not the entire tree, heapify-down operation is less expensive than
For
For
For
Therefore, total work is
Therefore,
Time complexity :
When doing a heapify-down in a min heap, we must keep in mind to swap with the smaller child, if both children violate property of BST.
This guarantees the correctness of both subtrees being valid heaps, and reduces unnecessary overhead.
Keep in mind
- A heap is not a sorted structure. Only root is guaranteed min/max, subtrees are not ordered.
- Heap is not a BST.
- Duplicate elements are generally fine.
Applications
- Heap Sort
- Prim's Algorithm
- Priority queue