Heap Operations
All max-heap operations run in time, where is the number of elements in the heap. Each operation works by traversing a single path from root to leaf (or leaf to root), bounded by the heap height .
Max-Heapify (Bubble-Down)
Purpose: Restore the max-heap property at node , assuming the subtrees rooted at ‘s children are already valid max-heaps.
Algorithm:
- Let , .
- Set
largestto if (or exceeds heap size), else to . - If is within heap and , set
largestto . - If
largest, swap and , then recursively call Max-Heapify onlargest.
Time: — each swap moves down one level, at most the height of the heap.
Walkthrough
Starting with a heap violation at the root: (node , children and ):
| Step | Current node | Children | Largest | Action |
|---|---|---|---|---|
| 1 | at index 1 | , | at index 2 | Swap 4 and 14 |
| 2 | at index 2 | , | at index 4 | Swap 4 and 8 |
| 3 | at index 4 | , | at index 4 | No swap; done |
Result: — a valid max-heap.
Insert (Bubble-Up)
Purpose: Insert a new key into the heap.
Algorithm:
- Increment
heap_size; place the new key at . - Set .
- While and :
- Swap and .
- .
Time: — at most one swap per level up to the root.
Extract-Max
Purpose: Remove and return the largest element (the root).
Algorithm:
- If the heap is empty, error.
- Store (the maximum).
- Swap with .
- Decrement
heap_size. - Call Max-Heapify on the root (index 1).
- Return stored maximum.
Time: — constant work plus one Max-Heapify call.
The swap with the last element preserves the structural property (only the rightmost bottom element can be removed without breaking completeness). The heap property is fixed by bubbling the new root downwards.
Increase-Key (Bubble-Up)
Purpose: Increase the value of a key at position , then restore the heap property by moving it upward.
Algorithm:
- If new value < current value, error.
- Set to new value.
- While and :
- Swap and .
- .
Time: .
Max-Peek
Simply return in time. No modification to the heap.
Operations Summary
| Operation | Purpose | Time | Method |
|---|---|---|---|
| Max-Heapify | Fix a single violation | Bubble down | |
| Insert | Add new element | Add at end, bubble up | |
| Extract-Max | Remove and return max | Swap with last, bubble down | |
| Increase-Key | Update to larger value | Update, bubble up | |
| Max-Peek | View maximum | Read |
All operations rely on the heap height being , ensuring each upward or downward traversal touches at most nodes.