Free explainer · Video · Code · Quiz
Heap Sort
Treat the array as a binary tree, build a max-heap with siftDown, then keep swapping the biggest value to the end and repairing the shrinking heap. In place, O(n log n) in the worst case, O(1) extra space.
- Difficulty
- Medium
- Time
- O(n log n)
- Space
- O(1)
Try it yourself
Step through it at your own pace — this is Heap Sort Animation, running right on the page.
LiveHeap Sort Animation
Loading the preview…
How it works
The idea, a worked example, and the traps to avoid.
The idea
Picture a tournament bracket where the winner of every match is the bigger of its two players. Whoever stands at the top is the biggest of all. Take that champion out, put it at the very end of the line, and replay only the matches along one path to crown a new champion. Repeat, and the line fills up from the back, biggest first. That's heap sort.
The bracket is a max-heap: a tree where every parent is at least as big as its children. It's not sorted (a parent's two children can be in either order), but it always keeps the maximum at the root, and fixing it after the root changes costs only one walk down the tree. That cheap "give me the biggest" operation is the whole trick.
The array is the tree
You don't need nodes or pointers. A complete binary tree (every level full except maybe the last, filled left to right) fits into an array with plain arithmetic:
- the children of index
iare at2i + 1and2i + 2; - the parent of index
iis atfloor((i - 1) / 2).
For [7, 2, 9, 4, 3, 8, 1] that gives this tree:
7 index 0
/ \
2 9 index 1, 2
/ \ / \
4 3 8 1 index 3, 4, 5, 6
The heap lives in the front of the array, and the sorted part grows from the back. The two never need separate memory.
Walkthrough
Phase 1: build the max-heap. siftDown(values, root, size) takes a value and sinks it: compare it with its bigger child, and if the child is bigger, swap and continue from there. We call it on every parent, from the last one back to index 0. For 7 values the last parent is index floor(7 / 2) - 1 = 2.
| Root | What happens | Array |
|---|---|---|
| 2 | children 8 and 1: the 9 is big enough, stays | [7, 2, 9, 4, 3, 8, 1] |
| 1 | children 4 and 3: the 2 swaps with the bigger one, 4 | [7, 4, 9, 2, 3, 8, 1] |
| 0 | children 4 and 9: 7 swaps with 9, then at index 2 meets 8 and 1 and swaps with 8 | [9, 4, 8, 2, 3, 7, 1] |
Going from the last parent back to the root matters: when we reach a value, both subtrees below it are already heaps, so one sink is enough to fix it.
Phase 2: sort. The root is the biggest value. Swap it with the last value of the heap, and that position is final. The heap is one shorter now, and its new root is probably too small, so sift it down within the smaller heap.
end |
After the swap | After siftDown (heap is the part left of end) |
|---|---|---|
| 6 | [1, 4, 8, 2, 3, 7, 9] |
[8, 4, 7, 2, 3, 1, 9] |
| 5 | [1, 4, 7, 2, 3, 8, 9] |
[7, 4, 1, 2, 3, 8, 9] |
| 4 | [3, 4, 1, 2, 7, 8, 9] |
[4, 3, 1, 2, 7, 8, 9] |
| 3 | [2, 3, 1, 4, 7, 8, 9] |
[3, 2, 1, 4, 7, 8, 9] |
| 2 | [1, 2, 3, 4, 7, 8, 9] |
[2, 1, 3, 4, 7, 8, 9] |
| 1 | [1, 2, 3, 4, 7, 8, 9] |
nothing left to sift |
The loop stops at end = 1: a heap of one value is already in place.
The choices in this code
One siftDown for both phases. Phase 1 calls it with size equal to the array length; phase 2 calls it with size = end, so the sorted tail is simply out of reach. No copying, no slicing.
Ties are fixed. Between two equal children biggerChild picks the left one, and a parent that equals its bigger child stays put (>=, not >). That keeps every run deterministic: the same swaps, in the same order, in every language.
Bottom-up instead of inserting one by one. You could build the heap by pushing values in one at a time (sift up), but that costs O(n log n). Sinking from the last parent is O(n), as explained below.
Why it's correct
After phase 1 every parent is ≥ its children, so the root is the maximum. In phase 2 each round moves the maximum of the remaining heap to its final index. Then siftDown restores the heap property: the new root's two subtrees are still heaps (we only removed a leaf and replaced the root), and sinking along the bigger child's path puts every value above its children again. After n - 1 rounds, the back of the array holds the values in ascending order and one value is left in front.
Complexity
- Phase 2: O(n log n).
n - 1sifts, and a sift walks down at most the height of the tree, about log₂ n levels. - Phase 1: O(n), not O(n log n). Half of all nodes are leaves and never move. A quarter sink at most one level, an eighth at most two, and so on. The total work is a series that adds up to less than 2n. Most nodes are near the bottom, where sinking is cheap.
- Time: O(n log n) in the best, average and worst case. No input makes it quadratic, which is its edge over quick sort. It doesn't speed up on nearly sorted data either.
- Space: O(1). Everything happens inside the array, and the loops need no recursion.
- Not stable. The swap of the root with the last value jumps over everything in between. Sorting
[2, 2, 1]with the two 2s labelledaandbgives[1, 2b, 2a]. Use merge sort when equal items must keep their order.
In practice heap sort is usually slower than quick sort on arrays, because it hops around memory (index i to 2i + 1), which caches dislike. You pick it for its guarantees.
Common bugs
- Wrong child indices. With 0-based arrays it's
2i + 1and2i + 2. The2iand2i + 1formulas belong to 1-based heaps. - Starting the build at
size - 1, or atsize / 2. The first parent isfloor(size / 2) - 1. Leaves have nothing to sink. - Reading a missing right child. When
2i + 2 >= size, there is only a left child. Compare againstsize, notvalues.length, or you drag sorted values back into the heap. - Forgetting the heap shrank. After the swap,
siftDownmust getend, not the old size. - Overflow in
2 * parent + 1in Java or C++ for arrays near 2³⁰ values. Rarely a concern, but it's why some code useslong.
When to use it (and when not)
Use it when you need a guaranteed O(n log n) with no extra memory: embedded code, or as the fallback that stops introsort from going quadratic (C++'s std::sort does exactly this). Look elsewhere for stability (merge sort) or the best speed on ordinary arrays (quick sort or the built-in sort).
The data structure behind it: the binary heap
The same array layout is a binary heap, the usual way to build a priority queue:
- peek the biggest: read index 0, O(1);
- pop the biggest: swap the root with the last value, shrink by one,
siftDown: O(log n). That's one round of phase 2; - push a value: add it at the end and sift it up while it's bigger than its parent: O(log n).
Dijkstra's algorithm, task schedulers and "top k" queries all run on this. Heap sort is just "build a heap, then pop everything".
Interview variations
- K largest elements. Keep a min-heap of size k: push each value, pop the smallest when the heap grows past k. O(n log k) time, O(k) space, and it works on a stream.
- Merge k sorted lists. Keep the current head of each list in a min-heap, pop the smallest, push the next value from the same list. O(N log k) for N values in total.
- Median of a stream. Two heaps: a max-heap for the lower half, a min-heap for the upper half. The median sits at one of the roots.
- Is this array a valid max-heap? For every index
i > 0, checkvalues[floor((i - 1) / 2)] >= values[i]. One pass.
Code
The same algorithm, step for step, in 4 languages.
// Heap sort, in place: build a max-heap, then keep moving the biggest value to the end.
// The array doubles as a complete binary tree: the children of index i sit at 2i + 1 and 2i + 2.
/**
* Sorts `values` in ascending order, in place.
* Not stable: equal values may end up in a different order than they started.
*
* @param {number[]} values the array to sort
* @returns {void}
*/
export function heapSort(values) {
const size = values.length;
// Phase 1: turn the array into a max-heap, from the last parent back to the root.
for (let root = Math.floor(size / 2) - 1; root >= 0; root--) {
siftDown(values, root, size);
}
// Phase 2: the root is the biggest value left. Park it at the end, then repair the heap.
for (let end = size - 1; end > 0; end--) {
swap(values, 0, end);
siftDown(values, 0, end); // the heap is now values[0..end - 1]
}
}
/**
* Sinks values[root] until both of its children are no bigger than it.
* Only values[0..size - 1] count as the heap; everything after is already sorted.
* Assumes the two subtrees under `root` are already max-heaps.
*
* @param {number[]} values
* @param {number} root index of the value to sink
* @param {number} size how many values at the front still belong to the heap
*/
export function siftDown(values, root, size) {
let parent = root;
while (true) {
const left = 2 * parent + 1;
if (left >= size) return; // no children: the value is a leaf, it stays
const child = biggerChild(values, left, size);
if (values[parent] >= values[child]) return; // the parent is big enough: heap restored
swap(values, parent, child); // the bigger child moves up, the parent sinks one level
parent = child;
}
}
/**
* Of the children `left` and `left + 1`, returns the index of the bigger one.
* A tie goes to the left child, and a missing right child is never read.
*
* @param {number[]} values
* @param {number} left index of the left child
* @param {number} size
* @returns {number}
*/
function biggerChild(values, left, size) {
const right = left + 1;
if (right >= size) return left; // only one child
return values[right] > values[left] ? right : left;
}
/**
* @param {number[]} values
* @param {number} a
* @param {number} b
*/
function swap(values, a, b) {
[values[a], values[b]] = [values[b], values[a]];
}
# Heap sort, in place: build a max-heap, then keep moving the biggest value to the end.
# The array doubles as a complete binary tree: the children of index i sit at 2i + 1 and 2i + 2.
from typing import List
def heap_sort(values: List[int]) -> None:
"""Sort values in ascending order, in place.
Not stable: equal values may end up in a different order than they started.
"""
size = len(values)
# Phase 1: turn the array into a max-heap, from the last parent back to the root.
for root in range(size // 2 - 1, -1, -1):
sift_down(values, root, size)
# Phase 2: the root is the biggest value left. Park it at the end, then repair the heap.
for end in range(size - 1, 0, -1):
_swap(values, 0, end)
sift_down(values, 0, end) # the heap is now values[0..end - 1]
def sift_down(values: List[int], root: int, size: int) -> None:
"""Sink values[root] until both of its children are no bigger than it.
Only values[0..size - 1] count as the heap; everything after is already
sorted. Assumes the two subtrees under root are already max-heaps.
"""
parent = root
while True:
left = 2 * parent + 1
if left >= size:
return # no children: the value is a leaf, it stays
child = _bigger_child(values, left, size)
if values[parent] >= values[child]:
return # the parent is big enough: heap restored
_swap(values, parent, child) # the bigger child moves up, the parent sinks one level
parent = child
def _bigger_child(values: List[int], left: int, size: int) -> int:
"""Of the children left and left + 1, return the index of the bigger one.
A tie goes to the left child, and a missing right child is never read.
"""
right = left + 1
if right >= size:
return left # only one child
return right if values[right] > values[left] else left
def _swap(values: List[int], a: int, b: int) -> None:
values[a], values[b] = values[b], values[a]
/**
* Heap sort, in place: build a max-heap, then keep moving the biggest value to the end.
* The array doubles as a complete binary tree: the children of index i sit at 2i + 1 and 2i + 2.
*/
public final class HeapSort {
private HeapSort() {
}
/**
* Sorts values in ascending order, in place.
* Not stable: equal values may end up in a different order than they started.
*/
public static void heapSort(int[] values) {
int size = values.length;
// Phase 1: turn the array into a max-heap, from the last parent back to the root.
for (int root = size / 2 - 1; root >= 0; root--) {
siftDown(values, root, size);
}
// Phase 2: the root is the biggest value left. Park it at the end, then repair the heap.
for (int end = size - 1; end > 0; end--) {
swap(values, 0, end);
siftDown(values, 0, end); // the heap is now values[0..end - 1]
}
}
/**
* Sinks values[root] until both of its children are no bigger than it.
* Only values[0..size - 1] count as the heap; everything after is already sorted.
* Assumes the two subtrees under root are already max-heaps.
*/
public static void siftDown(int[] values, int root, int size) {
int parent = root;
while (true) {
int left = 2 * parent + 1;
if (left >= size) {
return; // no children: the value is a leaf, it stays
}
int child = biggerChild(values, left, size);
if (values[parent] >= values[child]) {
return; // the parent is big enough: heap restored
}
swap(values, parent, child); // the bigger child moves up, the parent sinks one level
parent = child;
}
}
/**
* Of the children left and left + 1, returns the index of the bigger one.
* A tie goes to the left child, and a missing right child is never read.
*/
private static int biggerChild(int[] values, int left, int size) {
int right = left + 1;
if (right >= size) {
return left; // only one child
}
return values[right] > values[left] ? right : left;
}
private static void swap(int[] values, int a, int b) {
int tmp = values[a];
values[a] = values[b];
values[b] = tmp;
}
}
// Heap sort, in place: build a max-heap, then keep moving the biggest value to the end.
// The array doubles as a complete binary tree: the children of index i sit at 2i + 1 and 2i + 2.
// (In real code reach for std::make_heap and std::sort_heap, which do the same two phases.)
#include <utility>
#include <vector>
// Of the children left and left + 1, returns the index of the bigger one.
// A tie goes to the left child, and a missing right child is never read.
int biggerChild(const std::vector<int>& values, int left, int size) {
int right = left + 1;
if (right >= size) {
return left; // only one child
}
return values[right] > values[left] ? right : left;
}
// Sinks values[root] until both of its children are no bigger than it.
// Only values[0..size - 1] count as the heap; everything after is already sorted.
// Assumes the two subtrees under root are already max-heaps.
void siftDown(std::vector<int>& values, int root, int size) {
int parent = root;
while (true) {
int left = 2 * parent + 1;
if (left >= size) {
return; // no children: the value is a leaf, it stays
}
int child = biggerChild(values, left, size);
if (values[parent] >= values[child]) {
return; // the parent is big enough: heap restored
}
std::swap(values[parent], values[child]); // the bigger child moves up, the parent sinks one level
parent = child;
}
}
// Sorts values in ascending order, in place.
// Not stable: equal values may end up in a different order than they started.
void heapSort(std::vector<int>& values) {
int size = static_cast<int>(values.size());
// Phase 1: turn the array into a max-heap, from the last parent back to the root.
for (int root = size / 2 - 1; root >= 0; --root) {
siftDown(values, root, size);
}
// Phase 2: the root is the biggest value left. Park it at the end, then repair the heap.
for (int end = size - 1; end > 0; --end) {
std::swap(values[0], values[end]);
siftDown(values, 0, end); // the heap is now values[0..end - 1]
}
}
Test yourself
10 quick questions to check it stuck.
Q1 · In the array [7, 2, 9, 4, 3, 8, 1] viewed as a tree, which values are the children of the 9 at index 2?
Take it further
- Animation
Heap Sort Animation
The array and the binary tree it stands for, side by side: every sink moves both at once, the heap shrinks and the sorted tail locks in
Free
