In a heap, the Insertion and Deletion operations are crucial because they ensure the heap property is maintained after adding or removing elements. These operations are fundamental in algorithms like Heap Sort, Priority Queues, and Dijkstra's Shortest Path. Let's go through both operations in detail.
When you insert a new element into a heap, you must ensure that the heap property (whether max-heap or min-heap) is maintained after the insertion. The steps for inserting a new element are as follows:
Add the Element to the End:
Bubble Up (or Sift Up):
Suppose we have the following max-heap and want to insert 12:
20
/ \
15 10
/ \ /
8 6 5
Insert 12 at the end of the heap:
20
/ \
15 10
/ \ / \
8 6 5 12
Bubble up 12:
12 with its parent 10. Since 12 > 10, swap them: 20
/ \
15 12
/ \ / \
8 6 5 10
Bubble up 12 again:
12 with its new parent 15. Since 12 < 15, stop. No more swaps are needed.The final max-heap after insertion:
20
/ \
15 12
/ \ / \
8 6 5 10
Heap deletion typically refers to the operation where you remove the root element from the heap (either the maximum element in a max-heap or the minimum element in a min-heap) and then restore the heap property. In a max-heap, the root is the maximum element, while in a min-heap, it is the minimum element.
Swap the Root with the Last Element:
Remove the Last Element:
Heapify the Root:
Consider the following max-heap:
20
/ \
15 10
/ \ /
8 6 5
Swap the root with the last element:
20 with 5: 5
/ \
15 10
/ \ /
8 6 20
Remove the last element (which is now 20):
5
/ \
15 10
/ \
8 6
Heapify the root (5):
5 with its children (15 and 10). Since 15 is the largest child, swap 5 and 15: 15
/ \
5 10
/ \
8 6
5):
5 with its children (8 and 6). Since 8 is the largest child, swap 5 and 8: 15
/ \
8 10
/ \
5 6
The final max-heap after deletion:
15
/ \
8 10
/ \
5 6
Insertion:
Deletion:
Heap insertion and deletion are both logarithmic-time operations that maintain the heap property, ensuring that the heap is always a complete binary tree and that the root element is always the largest (in a max-heap) or smallest (in a min-heap). These operations are essential for applications like heap sort, priority queues, and other graph algorithms.
Open this section to load past papers