Data Structures · Visualization
Min-Heapify
Min Heap
Heapify fixes a single node that might violate the min-heap rule by sinking it into its 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).
Min-Heapify
Min HeapHeapify fixes a single node that might violate the min-heap rule by sinking it into its correct position, assuming its children are already valid heaps. Running heapify from the last non-leaf node up to the root converts any arbitrary array into a valid min-heap in linear time.
How Min-Heapify Works
- At the given node, compare its value with its left and right children.
- Find the smallest among the node and its two children.
- If the smallest 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.
Min-Heapify Worked Example
Input: Heapify node at index 0 in [30, 10, 20, 40]
- Node 30 (index 0), children 10 (index 1) and 20 (index 2)
- Smallest is 10, swap 30 and 10 → [10, 30, 20, 40]
- Continue heapify at index 1 (value 30): child is 40 (index 3), 30 < 40, no more swaps needed
Output: [10, 30, 20, 40]
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 [30, 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.
Min-Heapify Time & Space Complexity
When to Use Min-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-min
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.