Heap sort
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Heap sort builds a max heap, then repeatedly takes the biggest item and puts it at the end of the array, shrinking the heap by one each time. It sorts in place, needs almost no extra memory and has no nasty slow cases.
Practical use cases
- Web app: Sorting a large export on a small server. A reporting page sorts 2 million rows of a CSV on a cheap server with little memory. A method that needs a second copy of the data would run out of room. Heap sort rearranges the array in place, so the export finishes without crashing the server. The same approach works when the file doubles in size.
- Web app: Showing only the top 20 of a huge list. An analytics page needs just the 20 biggest orders of a million. After building the heap, taking 20 items from the top is enough, with no full sort. The report loads in a fraction of the time.
- System: Tiny devices and guaranteed speed. Embedded devices and real-time systems with tight memory use heap sort, because it sorts in place and its worst-case time is as predictable as its average. A car's control unit cannot afford a sort that sometimes turns slow.
The story: The Tallest Goes Last
Mrs. Sharma had to line up six kids by height for the annual photo, shortest to tallest. She was tired of bubble-style shuffling, and wanted a plan that used the pyramid trick her students learned in the heap module.
"First," she said, "make a pyramid with the tallest kid on top" (a max heap, built with the backwards sweep). "Now the tallest kid is certainly at the top. Send them to the last spot of the photo line, because that is exactly where the tallest kid belongs."
But who takes the tallest kid's place? The kid from the last spot of the pyramid! They are swapped, so the pyramid shrinks by one, and the new top may be wrong. So sink that kid (heapify) and the tallest of the remaining kids rises to the top. "Again!" Send the top to the second last spot. Repeat until the pyramid is down to one kid.
The whole lineup was sorted inside the very same array: the pyramid shrinks on the left, while the sorted photo line grows on the right. That is heap sort: build a max heap, then extract the max again and again, writing each one at the end.
How to spot this problem, and where you need it
You must sort a large list with very little spare memory, or you need a firm promise that the sort will never suddenly become slow on unlucky input.
Signs you need it
- A sort on a big dataset fails with "Allowed memory size exhausted" because it copies the data.
- You only need the top few items from a large set, so a complete sort wastes effort.
- The task asks for in-place sorting with guaranteed worst-case speed.
Where to use it in a project
- Memory-limited servers, scripts and devices sorting large logs or exports.
- Partial sorting for "top N" reports where you stop after N items.
The solution
First build a max heap from the array. Then repeat: swap the top (the biggest) with the last item of the heap area, shrink the heap area by one, and sink the new top into place. Each round puts one more biggest item in its final position at the end. When the heap area is gone, the array is sorted.
Payoff: Before: a sort needing double the memory and crashing at 2 million rows. After: the same array sorted in place, and the top 20 available after only 20 rounds.
Explain it like I am 8
Make a pyramid with the tallest kid on top. Send that kid to the back of the line. Rebuild the smaller pyramid, find its tallest kid, and send them second from the back. Keep going. The line grows at the back, the pyramid shrinks at the front, and in the end everyone is lined up by height.
How it works, step by step
- Build a max heap from the array (sift down from the last parent back to the root).
- Swap the root (the biggest) with the last item of the heap part. The biggest is now in its final seat.
- Shrink the heap by one, so the finished item is left alone.
- Sift down the new root to restore the max heap.
- Repeat steps 2 to 4 until the heap has only one item. The array is now sorted ascending.
The code in four languages
PHP
<?php
function siftDown(array &$a, int $n, int $i): void { // max-heap repair
while (true) {
$l = 2 * $i + 1; $r = $l + 1; $big = $i;
if ($l < $n && $a[$l] > $a[$big]) $big = $l;
if ($r < $n && $a[$r] > $a[$big]) $big = $r;
if ($big === $i) return;
[$a[$i], $a[$big]] = [$a[$big], $a[$i]];
$i = $big;
}
}
function heapSort(array $a): array {
$n = count($a);
for ($i = intdiv($n, 2) - 1; $i >= 0; $i--) siftDown($a, $n, $i); // 1) build a max heap
for ($end = $n - 1; $end > 0; $end--) {
[$a[0], $a[$end]] = [$a[$end], $a[0]]; // 2) biggest goes to its final seat
siftDown($a, $end, 0); // 3) heap is now one smaller: repair
}
return $a;
}
echo implode(' ', heapSort([5, 2, 9, 1, 7, 3])), PHP_EOL; // 1 2 3 5 7 9JavaScript
function siftDown(a, n, i) { // max-heap repair
for (;;) {
const l = 2 * i + 1, r = l + 1; let big = i;
if (l < n && a[l] > a[big]) big = l;
if (r < n && a[r] > a[big]) big = r;
if (big === i) return;
[a[i], a[big]] = [a[big], a[i]];
i = big;
}
}
function heapSort(input) {
const a = input.slice();
const n = a.length;
for (let i = (n >> 1) - 1; i >= 0; i--) siftDown(a, n, i); // 1) build a max heap
for (let end = n - 1; end > 0; end--) {
[a[0], a[end]] = [a[end], a[0]]; // 2) biggest goes to its final seat
siftDown(a, end, 0); // 3) heap is now one smaller: repair
}
return a;
}
console.log(heapSort([5, 2, 9, 1, 7, 3]).join(' ')); // 1 2 3 5 7 9Java
import java.util.Arrays;
public class Main {
static void siftDown(int[] a, int n, int i) { // max-heap repair
while (true) {
int l = 2 * i + 1, r = l + 1, big = i;
if (l < n && a[l] > a[big]) big = l;
if (r < n && a[r] > a[big]) big = r;
if (big == i) return;
int tmp = a[i]; a[i] = a[big]; a[big] = tmp;
i = big;
}
}
static int[] heapSort(int[] input) {
int[] a = input.clone();
int n = a.length;
for (int i = n / 2 - 1; i >= 0; i--) siftDown(a, n, i); // 1) build a max heap
for (int end = n - 1; end > 0; end--) {
int tmp = a[0]; a[0] = a[end]; a[end] = tmp; // 2) biggest goes to its final seat
siftDown(a, end, 0); // 3) heap is now one smaller: repair
}
return a;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(heapSort(new int[]{5, 2, 9, 1, 7, 3}))); // [1, 2, 3, 5, 7, 9]
}
}Go
package main
import "fmt"
// siftDown is the max-heap repair.
func siftDown(a []int, n, i int) {
for {
l, r, big := 2*i+1, 2*i+2, i
if l < n && a[l] > a[big] {
big = l
}
if r < n && a[r] > a[big] {
big = r
}
if big == i {
return
}
a[i], a[big] = a[big], a[i]
i = big
}
}
func heapSort(input []int) []int {
a := append([]int(nil), input...) // work on a copy
n := len(a)
for i := n/2 - 1; i >= 0; i-- { // 1) build a max heap
siftDown(a, n, i)
}
for end := n - 1; end > 0; end-- {
a[0], a[end] = a[end], a[0] // 2) biggest goes to its final seat
siftDown(a, end, 0) // 3) heap is now one smaller: repair
}
return a
}
func main() {
fmt.Println(heapSort([]int{5, 2, 9, 1, 7, 3})) // [1 2 3 5 7 9]
}Time: O(n log n) · Extra space: O(1). Build is O(n), then n extractions that each cost about log n. It sorts in place, but it is not stable (equal items may swap order).
Watch out for
- Using a min heap and expecting an ascending result in place. The in-place trick needs a max heap so the biggest lands at the end.
- Not shrinking the heap size after each swap, which sinks the finished items back into the heap.
- Assuming it is stable. Equal values can swap order because items jump from root to end.
Quick check
- For an ascending in-place heap sort we build a...
- Sorted array first
- Min heap
- Max heap
- After swapping the root with the last item, what must happen?
- Nothing
- Shrink the heap by one and sift down the new root
- Rebuild the whole heap
- Heap sort time and extra space?
- O(n²), O(1)
- O(n log n), O(n)
- O(n log n), O(1)