Build heap
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Building a heap turns an unordered list into a valid heap in one quick pass, by repairing parents from the bottom upward. It is much faster than inserting items one by one, and handy whenever you start with a big batch of data.
Practical use cases
- Web app: Turning a day of tickets into a queue. At 9 am a support tool loads 20,000 tickets from the database in no particular order and must hand out the most urgent first. Building the heap from the whole list in one pass is faster than adding tickets one at a time. Agents see the first urgent ticket almost immediately.
- Web app: Starting a priority queue from an uploaded CSV. A marketing admin uploads a CSV of 100,000 scheduled messages. The server must send the earliest first, so it builds a heap straight from the rows. The queue is ready in one sweep, and the page does not time out. The first message can start going out straight away.
- System: Heap sort and library helpers. Heap sort starts by turning the input into a heap. Many standard libraries offer a function such as heapify() or make_heap() that does this in one go, instead of looping over insert calls. Using it is usually the easiest speed-up.
The story: The Dabba Tower
In Mumbai, the dabbawalas deliver thousands of lunch boxes. Kabir was helping at a small tiffin centre where seven tags arrived in a jumble, each with a delivery time. The rule: the earliest time on the top, so the next dabba out is always obvious.
His first idea was to add tags one by one, letting each climb up as in the insert lesson. It works, but Zoya noticed something: "Half of these tags are at the bottom row, with no children at all. Each of those is already a tiny perfect heap!"
"So start above the bottom row," she said. "Take the last parent, fix it by sinking it down. Then step back to the parent before it, fix it. Keep going backwards until the top is fixed." By the time they reached the top, every sub-tree under it was already tidy, so sinking the top worked perfectly.
This backwards sweep is build heap. It turns any messy array into a heap in one pass, and surprisingly it is faster than inserting one by one, because most nodes are near the bottom and hardly have to move.
How to spot this problem, and where you need it
You are handed a big pile of items all at once and need a priority queue out of it, and inserting them one by one feels slower than it should.
Signs you need it
- A loop calls insert() for every item of a large array before you can use the queue.
- The task says "convert an array into a heap" or "build a priority queue from a list".
- Startup time of a job grows noticeably when the initial data set is large.
Where to use it in a project
- Loading a big batch of jobs, tickets or messages into a priority queue at start-up.
- The first phase of heap sort, or when preparing data for top-K queries.
The solution
Treat the array as a tree. The bottom half of the items are leaves and are already fine. Starting from the last parent and going backwards to the first item, fix each one with the move-down repair (heapify). By the time you reach the top, every part below is already a valid heap, so the whole array is one.
Payoff: Before: 100,000 separate inserts, each climbing the tree. After: one backwards sweep that does about twice as many steps as items, and the queue is ready.
Explain it like I am 8
You have a messy pile of building blocks. The blocks at the very bottom are already fine because they carry nothing. Start with the blocks just above them and make sure each one is lighter than what it carries. Then go one row up, and again, until you reach the top.
How it works, step by step
- Put all the items in an array, in any order.
- The second half of the array are leaves, so they are already heaps. Skip them.
- Find the last parent: the parent of the last item, at spot
n/2 - 1(rounded down). - Go backwards from that spot to spot 0 and run heapify (sift down) on each node.
- When you finish spot 0, the whole array is a valid heap.
The code in four languages
PHP
<?php
function siftDown(array &$a, int $n, int $i): void { // same repair as the heapify lesson
while (true) {
$l = 2 * $i + 1; $r = $l + 1; $small = $i;
if ($l < $n && $a[$l] < $a[$small]) $small = $l;
if ($r < $n && $a[$r] < $a[$small]) $small = $r;
if ($small === $i) return;
[$a[$i], $a[$small]] = [$a[$small], $a[$i]];
$i = $small;
}
}
function buildHeap(array &$a): void {
$n = count($a);
for ($i = intdiv($n, 2) - 1; $i >= 0; $i--) { // last parent, then backwards to the root
siftDown($a, $n, $i);
}
}
$tags = [9, 4, 7, 1, 6, 3, 8];
buildHeap($tags);
echo implode(' ', $tags), PHP_EOL; // 1 4 3 9 6 7 8JavaScript
function siftDown(a, n, i) { // same repair as the heapify lesson
for (;;) {
const l = 2 * i + 1, r = l + 1; let small = i;
if (l < n && a[l] < a[small]) small = l;
if (r < n && a[r] < a[small]) small = r;
if (small === i) return;
[a[i], a[small]] = [a[small], a[i]];
i = small;
}
}
function buildHeap(a) {
const n = a.length;
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { // last parent, then backwards to the root
siftDown(a, n, i);
}
}
const tags = [9, 4, 7, 1, 6, 3, 8];
buildHeap(tags);
console.log(tags.join(' ')); // 1 4 3 9 6 7 8Java
import java.util.Arrays;
public class Main {
static void siftDown(int[] a, int n, int i) { // same repair as the heapify lesson
while (true) {
int l = 2 * i + 1, r = l + 1, small = i;
if (l < n && a[l] < a[small]) small = l;
if (r < n && a[r] < a[small]) small = r;
if (small == i) return;
int tmp = a[i]; a[i] = a[small]; a[small] = tmp;
i = small;
}
}
static void buildHeap(int[] a) {
int n = a.length;
for (int i = n / 2 - 1; i >= 0; i--) { // last parent, then backwards to the root
siftDown(a, n, i);
}
}
public static void main(String[] args) {
int[] tags = {9, 4, 7, 1, 6, 3, 8};
buildHeap(tags);
System.out.println(Arrays.toString(tags)); // [1, 4, 3, 9, 6, 7, 8]
}
}Go
package main
import "fmt"
// siftDown is the same repair as the heapify lesson.
func siftDown(a []int, n, i int) {
for {
l, r, small := 2*i+1, 2*i+2, i
if l < n && a[l] < a[small] {
small = l
}
if r < n && a[r] < a[small] {
small = r
}
if small == i {
return
}
a[i], a[small] = a[small], a[i]
i = small
}
}
func buildHeap(a []int) {
n := len(a)
for i := n/2 - 1; i >= 0; i-- { // last parent, then backwards to the root
siftDown(a, n, i)
}
}
func main() {
tags := []int{9, 4, 7, 1, 6, 3, 8}
buildHeap(tags)
fmt.Println(tags) // [1 4 3 9 6 7 8]
}Time: O(n) · Extra space: O(1). Half the nodes are leaves that need no work, a quarter move at most one step, and so on, so the total stays proportional to n (better than n inserts, which is O(n log n)).
Watch out for
- Sweeping forwards from the root. The sub-trees under it must already be heaps before you sink the top, so go backwards.
- Starting at the last element instead of the last parent. Leaves have no children, so they need no work.
- Assuming "O(n log n)" because there is a loop with a sift inside. The careful count shows it is really O(n).
Quick check
- Where does build-heap start?
- At the root
- At the last parent
- At a random leaf
- In which direction does the loop run?
- From spot 0 to the end
- Both directions at once
- From the last parent back to spot 0
- Time to build a heap from n items this way?
- O(log n)
- O(n)
- O(n²)