Data Structures · Visualization
Max-Heap: Extract Max
Max Heap
Extracting the max removes and returns the root (the largest value), then repairs the heap: the last element in the array is moved to the root position, and it's 'sifted down' — repeatedly swapped with its larger child — until the heap rule holds again everywhere. Time: O(log n). Space: O(1) extra.
Big-O: Insert/extract O(log n); build O(n).
Max-Heap: Extract Max
Max HeapExtracting the max removes and returns the root (the largest value), then repairs the heap: the last element in the array is moved to the root position, and it's 'sifted down' — repeatedly swapped with its larger child — until the heap rule holds again everywhere.
How Extract Max Works
- Save the root value (index 0) — this is the maximum, to be returned.
- Move the last element in the array to the root position.
- Remove the now-duplicate last slot.
- Sift the new root down: compare it with its two children, swap with the larger child if it's bigger than the root, and repeat until the rule holds.
Extract Max Worked Example
Input: Extract max from [50, 30, 45, 10, 20, 40]
- Save max = 50
- Move last element (40) to the root: [40, 30, 45, 10, 20]
- Compare 40 with children 30 and 45: 45 is larger and bigger than 40, swap → [45, 30, 40, 10, 20]
- 40's new children (index 5, 6) don't exist, stop
Output: Removed: 50, heap now: [45, 30, 40, 10, 20]
Press ▶ Run to watch it step by step.
def extract_max(heap):
top = heap[0]
heap[0] = heap.pop() # move last to root
i, n = 0, len(heap)
while True:
l, r, big = 2*i+1, 2*i+2, i
if l < n and heap[l] > heap[big]:
big = l
if r < n and heap[r] > heap[big]:
big = r
if big == i:
break
heap[i], heap[big] = heap[big], heap[i] # sift down
i = big
return top
# O(log n)
# example: extract on [50, 30, 45, 10, 20, 40]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Extract Max Time & Space Complexity
When to Use Extract Max
- Serving the highest-priority task next in a scheduler
- Repeatedly pulling the largest remaining value, as in heap sort
- Running a 'top-k largest' style algorithm efficiently
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.