Merge Sort is always O(n log n), but needs a second array. Quick Sort sorts in place, but a bad pivot makes it O(n²). Heap Sort gets the best of both: it is O(n log n) in every case, and it sorts in place.
Its trick is to look at the array in a new way: as a tree.
By the end of this lesson, you will understand:
- How an array can be read as a binary tree
- What a max-heap is, and how to build one
- How Heap Sort uses the heap to sort
- How to trace it and write it in code
- Why it is always
O(n log n)
Reading an Array as a Tree
Picture the values of an array placed into a tree, row by row, from left to right. Position 0 is the top, called the root. Every position i has up to two children:
- the left child at
2i + 1 - the right child at
2i + 2
And the parent of position i is at (i - 1) / 2, rounded down.
Here is our array, [5, 1, 4, 2, 8], drawn as a tree. The small numbers are positions:
array: [5, 1, 4, 2, 8]
0 1 2 3 4
tree: 5 (0)
/ \
1 (1) 4 (2)
/ \
2 (3) 8 (4)
Nothing has moved. It is the same array, just pictured differently. Position 1's children are at 2 × 1 + 1 = 3 and 2 × 1 + 2 = 4, which hold 2 and 8.
What Is a Max-Heap?
A max-heap is a tree where every parent is at least as big as its children. That one rule has a powerful result: the biggest value is always at the root, position 0.
Our tree is not a max-heap yet. 1 is smaller than its child 8, and 5 is smaller than 8 too.
How Heap Sort Works
Heap Sort has two phases:
- Build a max-heap out of the array.
- Take the root out, again and again. Swap the root (the biggest value) with the last value of the heap. The biggest value is now in its final place at the end. The heap shrinks by one, and the new root is probably too small, so sift it down: swap it with its bigger child until it is at least as big as both its children.
The step that fixes one parent is called heapify, or sift down. Both phases are built from it.
Watch it below. The bubbles show the array, and the tree underneath shows the same values as a heap. The blue band marks the part of the array that is still the heap. Values that leave the heap turn green, fade in the tree, and never move again.
The Sports Tournament Analogy
Imagine ranking players by skill, with a knockout-style tree of matches.
1. Winners Move Up
Every match is between a parent and their children. The strongest of the three always moves up. Soon the strongest player of all sits at the top.
2. The Champion Leaves
The champion at the top is crowned and steps off the tree. They are in their final place in the ranking.
3. Refill the Top
The last player in the tree moves to the empty top spot. They are probably not the strongest, so they play their way down, losing to whoever is stronger, until they find their level.
4. Repeat
Now the strongest remaining player is at the top again. Crown them next, and repeat until everyone has a rank.
Tracing It by Hand
Let's sort [5, 1, 4, 2, 8].
Phase 1: Build the Max-Heap
Only positions with children need fixing. The last parent is at n / 2 - 1 = 5 / 2 - 1 = 1, rounded down. We fix parents from there back to the root, so each one is fixed after the parents below it.
| Fix parent | Its children | Bigger child? | Array after |
|---|---|---|---|
| 1 (value 1) | 2 and 8 | 8, so swap 1 and 8 | [5, 8, 4, 2, 1] |
| 0 (value 5) | 8 and 4 | 8, so swap 5 and 8 | [8, 5, 4, 2, 1] |
| 1 (value 5, again) | 2 and 1 | neither, so stop | [8, 5, 4, 2, 1] |
After 5 swapped down to position 1, it had to be checked again in its new spot. That "keep going down" is what heapify does.
max-heap: 8
/ \
5 4
/ \
2 1
Every parent is now at least as big as its children, and the biggest value, 8, is at the root. That took 6 comparisons and 2 swaps.
Phase 2: Take the Root Out, Again and Again
The | separates the heap (left) from the sorted part (right).
| Round | Swap the root to the end | Sift the new root down | Array after |
|---|---|---|---|
| 1 | 8 and 1: [1, 5, 4, 2 | 8] | 1 swaps with 5, then with 2 | [5, 2, 4, 1 | 8] |
| 2 | 5 and 1: [1, 2, 4 | 5, 8] | 1 swaps with 4 | [4, 2, 1 | 5, 8] |
| 3 | 4 and 1: [1, 2 | 4, 5, 8] | 1 swaps with 2 | [2, 1 | 4, 5, 8] |
| 4 | 2 and 1: [1 | 2, 4, 5, 8] | one value left, nothing to fix | [1, 2, 4, 5, 8] |
Each round, the biggest value left in the heap lands in its final place, just like Selection Sort. The difference is how it is found: Selection Sort scans every remaining value, while Heap Sort already has it waiting at the root.
The result is [1, 2, 4, 5, 8], in 12 comparisons and 10 swaps. That is actually more than Bubble Sort needed for the same array! On tiny arrays, building and fixing the heap costs more than it saves. Heap Sort's advantage shows as the data grows: for 1,000 values it needs around 17,000 comparisons, while a simple O(n²) sort can need nearly 500,000.
Heap Sort in Code
import java.util.Arrays;
public class Main {
static void heapSort(int[] a) {
int n = a.length;
for (int i = n / 2 - 1; i >= 0; i--) { // phase 1: build the max-heap
heapify(a, n, i);
}
for (int end = n - 1; end > 0; end--) { // phase 2: take the root out
int temp = a[0]; // move the biggest value to the end
a[0] = a[end];
a[end] = temp;
heapify(a, end, 0); // the heap is now one smaller: fix its root
}
}
// Sift a[i] down until it is at least as big as its children.
// Only the first `size` values are part of the heap.
static void heapify(int[] a, int size, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < size && a[left] > a[largest]) {
largest = left;
}
if (right < size && a[right] > a[largest]) {
largest = right;
}
if (largest != i) { // a child is bigger: swap and keep going down
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
heapify(a, size, largest);
}
}
public static void main(String[] args) {
int[] marks = {5, 1, 4, 2, 8};
heapSort(marks);
System.out.println(Arrays.toString(marks)); // [1, 2, 4, 5, 8]
}
}Let's connect the code to the trace:
- The first loop is Phase 1. It starts at
n / 2 - 1, the last position that has a child, and goes back to0. - The second loop is Phase 2.
endis the last position of the heap. Swappinga[0]anda[end]puts the biggest value in its final place. heapify(a, end, 0)passesendas the size, so the values already sorted at the back are no longer part of the heap.- In
heapify,largestends up as whichever of the parent and its two children is biggest. If that is a child, they swap, andheapifycarries on from the child's position. left < sizeandright < sizecheck that the child exists in the heap before reading it.
How Fast Is Heap Sort?
The tree is balanced: each row is full before the next one starts. So a heap of n values is only about log n rows tall. A sift down moves one row per swap, so it takes at most about log n steps.
| Case | Example | Time | Why |
|---|---|---|---|
| Best | Any order | O(n log n) | Every one of the n roots still has to come out, and each new root sifts down |
| Average | Random order | O(n log n) | Same as above |
| Worst | Any order | O(n log n) | A sift down never goes deeper than the tree's height, log n |
| Extra memory | Any | O(1) | Sorts in place. (The recursive heapify above uses up to log n stack frames; written as a loop, it needs none.) |
Building the heap in Phase 1 takes only O(n), because most parents sit near the bottom and sift down just a step or two. Phase 2 does the real work: n sift downs of up to log n steps each, so O(n log n).
Try Sorted and Reversed in the animation. Reversed [7, 6, 5, 4, 3, 2, 1] is already a max-heap, because every parent is bigger than the values after it, so Phase 1 makes no swaps at all. Even so, it takes 18 comparisons, and Sorted takes 21. Compare that with Insertion Sort, which needs just 6 on sorted data. Heap Sort is not adaptive: data that is already in order doesn't help it.
Heap Sort is not stable. Swapping the root with the last value jumps values over long distances. For example, sorting
[2a, 2b, 1]gives[1, 2b, 2a]: the two 2s swap their order.
Common Mistakes
1. Building the Heap in the Wrong Direction
Phase 1 must go from the last parent back to the root. If you go from the root forward instead, a big value near the bottom can only climb one row, and may never reach the top, so the result is not a max-heap.
2. Forgetting to Shrink the Heap
In Phase 2, call heapify(a, end, 0), not heapify(a, n, 0). With n, the sorted values at the back still count as part of the heap, and the biggest ones get pulled straight back to the root.
3. Reading a Child That Isn't There
Check left < sizebefore reading a[left], and the same for right. Near the bottom of the tree, a parent may have only one child, or none.
When Should You Use Heap Sort?
Good for:
- When you need a guaranteed
O(n log n)and can't spare extra memory - As a safety net: Introsort, which you met in the Quick Sort lesson, switches to Heap Sort when Quick Sort's recursion goes too deep. That is how C++'s
std::sortusually avoidsO(n²)
Not good for:
- Sorts that must be stable: use Merge Sort
- Nearly sorted data: Insertion Sort is much faster there
- Everyday speed: in practice, Quick Sort is usually faster, because it reads memory in order while Heap Sort jumps between parents and children
The heap itself is useful far beyond sorting. It is the idea behind the priority queue, which always hands you the most important item first. You will meet it again later in this masterclass.
That completes our tour of sorting! You now know three simple O(n²) algorithms and three efficient O(n log n) ones, and you can see why real libraries combine their best ideas.
In the next section, Searching, you'll see one of the biggest rewards of sorted data: Binary Search, which finds any value among a million sorted values in at most 20 checks.
Remember This
If you remember only one thing from this lesson, remember: Heap Sort builds a max-heap so the biggest value sits at the root, then swaps the root to the end and sifts the new root down, again and again. It is O(n log n) in every case and sorts in place, but it is not stable.