Data Structures · Visualization
Max-Heapify
Max Heap
Heapify is the process of fixing a single node that might violate the max-heap rule, by sinking it down into the correct position, assuming its children are already valid heaps. Time: O(log n) for one call, O(n) to heapify an entire array (build-heap). Space: O(1) extra iterative, O(log n) recursive.
Big-O: Insert/extract O(log n); build O(n).
Max-Heapify
Max HeapHeapify is the process of fixing a single node that might violate the max-heap rule, by sinking it down into the correct position, assuming its children are already valid heaps. Running heapify from the last non-leaf node up to the root efficiently converts any arbitrary array into a valid max-heap in linear time.
How Max-Heapify Works
- At the given node, compare its value with its left and right children.
- Find the largest among the node and its two children.
- If the largest is not the current node, swap the node with that child.
- Recursively (or iteratively) apply heapify at the position the node was swapped into, since that subtree may now be violated.
Max-Heapify Worked Example
Input: Heapify node at index 0 in [10, 40, 30, 5]
- Node 10 (index 0), children 40 (index 1) and 30 (index 2)
- Largest is 40, swap 10 and 40 → [40, 10, 30, 5]
- Continue heapify at index 1 (value 10): child is 5 (index 3), 10 > 5, no more swaps needed
Output: [40, 10, 30, 5]
Press ▶ Run to watch it step by step.
def heapify(a):
n = len(a)
def sift(i):
while True:
l, r, big = 2*i+1, 2*i+2, i
if l < n and a[l] > a[big]:
big = l
if r < n and a[r] > a[big]:
big = r
if big == i:
break
a[i], a[big] = a[big], a[i]
i = big
for i in range(n // 2 - 1, -1, -1):
sift(i) # fix each subtree
return a
# Builds a max-heap in O(n)
# example: heapify 0 on [10, 40, 30, 5]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.
Max-Heapify Time & Space Complexity
When to Use Max-Heapify
- Building a heap from an unsorted array efficiently (heap construction)
- Restoring heap order after replacing the root's value directly
- The core repair step used inside both insert and extract-max
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.