Heaps
Heaps
Heaps
A B C D E F G H I J (B)
0 1 2 3 4 5 6 7 8 9 10 11 12 13
(A)
Array Implementation
13 21 16 24 31 19 68 65 26 32
0 1 2 3 4 5 6 7 8 9 10 11 12 13
•Create a new child node at the end of the heap (last level).
•Add the new key to that node (append it to the array).
•Move the child up until you reach the root node and the heap
property is satisfied.
Percolate by swapping
The newly added value is compared with its parent (using the formula
(hole - 1) / 2).
• If the new value is smaller than the parent, the positions are
swapped to restore the Min-Heap property.
• This process continues until the new value is greater than or
equal to its parent, or the new value becomes the root.
Step 1: Insert 10
• Heap: [10] (only one element, so it’s already a valid Min-Heap).
Step 2: Insert 20
• New value 20 is added to the end: [10, 20].No swap needed since 20 > 10.
Step 3: Insert 5
• New value 5 is added: [10, 20, 5].
• Percolate up:5 is smaller than 10 (its parent), so they are swapped.
• Final Heap: [5, 20, 10].
Step 4: Insert 15
• New value 15 is added: [5, 20, 10, 15].
• Percolate up:15 is smaller than 20 (its parent), so they are swapped.
• Final Heap: [5, 15, 10, 20].
BOOK 30
BOOK 5
BOOK 21
Output Terminal
Instruction:
Program a medium-sized C++ code similar to the sample code provided for a MinHeap. This
time, implement a MaxHeap, ensuring that the value of each parent node is greater than or
equal to the values of its child nodes (left and right).