Heapify
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Heapify fixes a single out-of-place item in a heap by moving it down, one level at a time, swapping with its smaller or larger child until the heap rule holds again. It is the repair step that every other heap operation relies on.
Practical use cases
- Web app: Updating a task priority. In a task board, a manager changes a ticket from "low" to "urgent", and the ticket must move to the right place in the waiting queue. The app adjusts only that ticket by moving it up or down a few levels. The rest of the 10,000 tickets are not touched.
- Web app: Delivery order whose time estimate changes. A food-delivery dispatcher keeps pending orders ordered by promised time. When traffic changes one order estimate, only that order needs fixing. A short downward repair restores the queue so the next rider is always assigned the most urgent order. Riders spend less time waiting at the restaurant.
- System: Database engines and heap operations. Removing the top of a heap leaves a wrong item at the root, and heapify repairs it. Database engines and libraries that keep priority queues use this small repair after almost every change. Because it touches only one path, it adds almost no delay.
The story: The Wrong Name on the Throne
At Mira's school sports day, the events were run from a pyramid of numbered cards, with the smallest number on top, so the next event was always the card on top. Just before the final, a card with the big number 9 was placed at the top by mistake.
Everything under the top was still perfectly arranged. The two sub-pyramids were fine, only the very top was wrong. Mrs. Sharma said, "Don't rebuild the whole pyramid. Let card 9 sink."
Card 9 looked at the two below it, 3 and 5. "Swap with the smaller one," said Mrs. Sharma, "so that the smaller number becomes the boss of the other." 9 swapped with 3 and then looked at its new children, 4 and 6. Swapped with 4. Now it was at the bottom with no children. Done in two swaps!
That sinking move has a name: heapify. It repairs a heap when only one node, usually the root, is out of place.
How to spot this problem, and where you need it
One item in a priority structure has a wrong value or position, and you need the structure to be correct again without rebuilding everything from scratch.
Signs you need it
- You changed the priority, time or score of one item and the top of the queue is no longer the right one.
- Your fix is to rebuild or re-sort the whole queue after a single small change.
- The problem says "restore the heap property" or "sift down".
Where to use it in a project
- Task and ticket queues where one item changes priority at a time.
- Schedulers and dispatchers where a time or cost estimate for one item is updated.
The solution
Look at the item and its two children. If a child is smaller (for a min heap), swap the item with the smaller child. Continue from the item's new position, and stop when it is no longer bigger than its children or has none. Only one path from the item to the bottom is touched.
Payoff: Before: re-sorting 10,000 tickets after one change. After: about 13 swaps at most, and the queue is correct.
Explain it like I am 8
A heavy kid sits on top of a pyramid of lighter kids, and the pyramid wobbles. The heavy kid steps down, one level at a time, always swapping places with the lighter kid below, until they reach a spot where no one lighter is beneath them.
How it works, step by step
- Start at the misplaced node (the top, in the usual case).
- Look at its two children and pick the smaller one (for a min heap).
- If the node is bigger than that child, swap them. If not, stop: it is home.
- Continue from the node's new position one level lower, and repeat.
- You stop at a leaf at the latest, so you walk down at most the height of the tree.
The code in four languages
PHP
<?php
// Sink the value at spot $i until neither child is smaller (min heap).
function heapify(array &$a, int $n, int $i): void {
while (true) {
$left = 2 * $i + 1;
$right = 2 * $i + 2;
$smallest = $i;
if ($left < $n && $a[$left] < $a[$smallest]) $smallest = $left;
if ($right < $n && $a[$right] < $a[$smallest]) $smallest = $right;
if ($smallest === $i) return; // already smaller than both children: home
[$a[$i], $a[$smallest]] = [$a[$smallest], $a[$i]]; // swap with the smaller child
$i = $smallest; // keep sinking
}
}
$quotes = [9, 3, 5, 4, 6, 8, 7]; // 9 is wrongly on the throne
heapify($quotes, count($quotes), 0);
echo implode(' ', $quotes), PHP_EOL; // 3 4 5 9 6 8 7JavaScript
// Sink the value at spot i until neither child is smaller (min heap).
function heapify(a, n, i) {
for (;;) {
const left = 2 * i + 1;
const right = 2 * i + 2;
let smallest = i;
if (left < n && a[left] < a[smallest]) smallest = left;
if (right < n && a[right] < a[smallest]) smallest = right;
if (smallest === i) return; // already smaller than both children: home
[a[i], a[smallest]] = [a[smallest], a[i]]; // swap with the smaller child
i = smallest; // keep sinking
}
}
const quotes = [9, 3, 5, 4, 6, 8, 7]; // 9 is wrongly on the throne
heapify(quotes, quotes.length, 0);
console.log(quotes.join(' ')); // 3 4 5 9 6 8 7Java
import java.util.Arrays;
public class Main {
// Sink the value at spot i until neither child is smaller (min heap).
static void heapify(int[] a, int n, int i) {
while (true) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int smallest = i;
if (left < n && a[left] < a[smallest]) smallest = left;
if (right < n && a[right] < a[smallest]) smallest = right;
if (smallest == i) return; // already smaller than both children: home
int tmp = a[i]; a[i] = a[smallest]; a[smallest] = tmp; // swap with the smaller child
i = smallest; // keep sinking
}
}
public static void main(String[] args) {
int[] quotes = {9, 3, 5, 4, 6, 8, 7}; // 9 is wrongly on the throne
heapify(quotes, quotes.length, 0);
System.out.println(Arrays.toString(quotes)); // [3, 4, 5, 9, 6, 8, 7]
}
}Go
package main
import "fmt"
// heapify sinks the value at spot i until neither child is smaller (min heap).
func heapify(a []int, n, i int) {
for {
left := 2*i + 1
right := 2*i + 2
smallest := i
if left < n && a[left] < a[smallest] {
smallest = left
}
if right < n && a[right] < a[smallest] {
smallest = right
}
if smallest == i { // already smaller than both children: home
return
}
a[i], a[smallest] = a[smallest], a[i] // swap with the smaller child
i = smallest // keep sinking
}
}
func main() {
quotes := []int{9, 3, 5, 4, 6, 8, 7} // 9 is wrongly on the throne
heapify(quotes, len(quotes), 0)
fmt.Println(quotes) // [3 4 5 9 6 8 7]
}Time: O(log n) · Extra space: O(1). The node walks down one branch, and a tidy tree is only about log n levels tall (every level doubles the number of seats).
Watch out for
- Swapping with the bigger child in a min heap. Then the other child would end up below something bigger than itself.
- Forgetting to compare with both children, or reading past the end of the array when a node has only one child.
- Using heapify on a completely messy array and expecting it to fix everything. It only repairs one misplaced node whose sub-trees are already heaps.
Quick check
- In a min heap, the misplaced node sinks. It swaps with which child?
- The smaller child
- Always the left child
- The bigger child
- When does the sinking stop?
- Only at the root
- After exactly one swap
- When the node is not bigger than its children (or is a leaf)
- Heapify assumes what about the two sub-trees under the misplaced node?
- They are empty
- They are already valid heaps
- They are sorted