Heap sort
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Heap sort arranges items in a pyramid where the biggest sits on top, then repeatedly removes the top and rebuilds the pyramid. It never slows down badly, uses no extra memory, and the same pyramid idea powers priority queues.
Practical use cases
- Web app: Top 10 sellers from millions of orders. A dashboard wants the 10 best-selling products from a huge stream of sales. A small heap of 10 items keeps the best so far, replacing the weakest whenever a better one arrives. The widget stays accurate without sorting millions of rows.
- Web app: Task scheduler picks the most urgent job. A support tool must always show the most urgent ticket next, while tickets keep arriving. A heap keeps the most urgent on top, so picking it is instant and adding a ticket is cheap. Agents never wait for a full re-sort.
- System: Shortest path and guaranteed-speed sorting. Route finders such as Dijkstra use heaps to choose the next closest place quickly. Systems that need a guaranteed worst-case time, like some embedded devices, pick heap sort because it never goes slow on unlucky data. In both cases the heap always knows who comes next without re-sorting a whole list.
The story: The Pyramid of Winners
At the school sports day, Zoya's class built a human pyramid, with the strongest child at the top and weaker ones below, each child standing on two others. The rule was simple: nobody may be stronger than the child they stand on.
That gave Mrs. Sharma an idea for ranking the class. "Whoever is at the top is the strongest. Let them step down and take the last place in the ranking. Now, to fix the gap, bring the last child up to the top. They will be wobbly: if a child below is stronger, swap! Keep swapping down until the pyramid holds again."
Each time, the top of the pyramid hands over the next strongest child, and the pyramid repairs itself in only a few swaps because it is short and wide, never tall and thin. After everyone has stepped down, the ranking is complete.
This pyramid is called a heap, and ranking by repeatedly taking the top is heap sort. Better still, the pyramid lives inside the very same row of numbers, so it needs no extra space.
How to spot this problem, and where you need it
You repeatedly need the biggest or smallest item from a changing collection, or you need a sort that never slows down badly and uses almost no extra memory.
Signs you need it
- The problem says "priority queue", "top k", "k largest", "next most urgent" or "always remove the maximum".
- You keep re-sorting a list after every insert just to read its first element.
- Memory is tight, or you need a sort whose speed does not depend on how the data happens to be arranged.
Where to use it in a project
- Leaderboards, trending lists and top-N widgets built from large streams of events.
- Job queues and schedulers where the most urgent item must come out first.
The solution
Build a heap: a pyramid where each parent is bigger than its children, so the biggest item is on top. To sort, swap the top with the last item, shrink the pyramid by one, and let the new top sink down to restore the rule. Repeat until the pyramid is empty. For top-k, keep a small heap of size k and replace its weakest member when something better arrives.
Payoff: Before: re-sorting millions of rows to show 10 best sellers. After: a 10-item heap updated per order, nearly instant.
Explain it like I am 8
Imagine a pyramid where each kid stands on two kids who are weaker. The strongest kid is always on top. Let the top kid go to the end of the line, move the last kid up, then let them sink down until the pyramid is right again. Keep doing that and the line forms in order.
How it works, step by step
- View the array as a tree: item
ihas children at2i+1and2i+2. - Build a max-heap: from the last parent back to the first, sift each one down (swap it with its bigger child while that child is bigger).
- Swap the top (biggest) with the last item of the heap. The biggest is now final, so shrink the heap by one.
- Sift down the new top until the heap rule holds again.
- Repeat until the heap has one item left. The array is sorted ascending.
The code in four languages
PHP
<?php
// Heap sort: build a max-heap inside the array, then peel off the biggest repeatedly.
function siftDown(array &$a, int $i, int $size): void {
while (true) {
$left = 2 * $i + 1;
$right = $left + 1;
$big = $i;
if ($left < $size && $a[$left] > $a[$big]) $big = $left;
if ($right < $size && $a[$right] > $a[$big]) $big = $right;
if ($big === $i) return; // parent already beats both children
[$a[$i], $a[$big]] = [$a[$big], $a[$i]];
$i = $big; // keep sinking
}
}
function heapSort(array $a): array {
$n = count($a);
for ($i = intdiv($n, 2) - 1; $i >= 0; $i--) {
siftDown($a, $i, $n); // build the heap
}
for ($end = $n - 1; $end >= 1; $end--) {
[$a[0], $a[$end]] = [$a[$end], $a[0]]; // biggest goes to its final place
siftDown($a, 0, $end); // repair the smaller heap
}
return $a;
}
echo implode(', ', heapSort([4, 1, 3, 5, 2])); // 1, 2, 3, 4, 5JavaScript
// Heap sort: build a max-heap inside the array, then peel off the biggest repeatedly.
function siftDown(a, i, size) {
while (true) {
const left = 2 * i + 1, right = left + 1;
let big = i;
if (left < size && a[left] > a[big]) big = left;
if (right < size && a[right] > a[big]) big = right;
if (big === i) return; // parent already beats both children
[a[i], a[big]] = [a[big], a[i]];
i = big; // keep sinking
}
}
function heapSort(input) {
const a = [...input];
const n = a.length;
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
siftDown(a, i, n); // build the heap
}
for (let end = n - 1; end >= 1; end--) {
[a[0], a[end]] = [a[end], a[0]]; // biggest goes to its final place
siftDown(a, 0, end); // repair the smaller heap
}
return a;
}
console.log(heapSort([4, 1, 3, 5, 2]).join(', ')); // 1, 2, 3, 4, 5Java
import java.util.*;
import java.util.stream.*;
public class Main {
// Heap sort: build a max-heap inside the array, then peel off the biggest repeatedly.
static void siftDown(int[] a, int i, int size) {
while (true) {
int left = 2 * i + 1, right = left + 1;
int big = i;
if (left < size && a[left] > a[big]) big = left;
if (right < size && a[right] > a[big]) big = right;
if (big == i) return; // parent already beats both children
int tmp = a[i]; a[i] = a[big]; a[big] = tmp;
i = big; // keep sinking
}
}
static int[] heapSort(int[] input) {
int[] a = Arrays.copyOf(input, input.length);
int n = a.length;
for (int i = n / 2 - 1; i >= 0; i--) {
siftDown(a, i, n); // build the heap
}
for (int end = n - 1; end >= 1; end--) {
int tmp = a[0]; a[0] = a[end]; a[end] = tmp; // biggest goes to its final place
siftDown(a, 0, end); // repair the smaller heap
}
return a;
}
// Joins the numbers with a separator, e.g. "1, 2, 3".
static String join(int[] a, String sep) {
return Arrays.stream(a).mapToObj(String::valueOf).collect(Collectors.joining(sep));
}
public static void main(String[] args) {
System.out.println(join(heapSort(new int[]{4, 1, 3, 5, 2}), ", ")); // 1, 2, 3, 4, 5
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// Heap sort: build a max-heap inside the slice, then peel off the biggest repeatedly.
func siftDown(a []int, i, size int) {
for {
left := 2*i + 1
right := left + 1
big := i
if left < size && a[left] > a[big] {
big = left
}
if right < size && a[right] > a[big] {
big = right
}
if big == i {
return // parent already beats both children
}
a[i], a[big] = a[big], a[i]
i = big // keep sinking
}
}
func heapSort(input []int) []int {
a := append([]int(nil), input...)
n := len(a)
for i := n/2 - 1; i >= 0; i-- {
siftDown(a, i, n) // build the heap
}
for end := n - 1; end >= 1; end-- {
a[0], a[end] = a[end], a[0] // biggest goes to its final place
siftDown(a, 0, end) // repair the smaller heap
}
return a
}
// join glues the numbers together with a separator, e.g. "1, 2, 3".
func join(a []int, sep string) string {
parts := make([]string, len(a))
for i, v := range a {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, sep)
}
func main() {
fmt.Println(join(heapSort([]int{4, 1, 3, 5, 2}), ", ")) // 1, 2, 3, 4, 5
}Time: O(n log n) · Extra space: O(1). A heap is only about log n levels tall, so each repair is short. It sorts in place, but it is not stable.
Watch out for
- Sifting down to the wrong boundary. After swapping, the heap size is
end, so the finished items must not be touched. - Swapping with the first child that is bigger instead of the bigger of the two children.
- Forgetting the build phase. Extracting from an array that is not yet a heap gives wrong answers.
Quick check
- In an array-based heap, where are the children of the item at index 1?
- Indexes 3 and 4
- Indexes 0 and 1
- Indexes 2 and 3
- What sits at the top of a max-heap?
- The smallest item
- The middle item
- The biggest item
- Which statement about heap sort is true?
- It needs a second array
- It sorts in place with O(n log n) worst case
- It is the fastest on sorted data