Heap sort is an in-place sorting algorithm that turns an array into a max heap, then repeatedly swaps the root, the largest value, to the end of the heap and sifts the new root down, so the sorted part grows from the right. It takes O(n log n) time even in the worst case, needs O(1) extra space and is not stable. This page explains how it works, with step-by-step animations of building the max heap, the first extractions and the remaining extractions from the VisiGrab app.
// how heap sort works
Heap sort is an in-place sorting algorithm that turns an array into a max heap, a binary tree stored in the array with the largest value at the root. It then repeatedly swaps the root to the end and repairs the smaller heap. It takes O(n log n) time even in the worst case and O(1) extra space, and it is not stable. J. W. J. Williams invented it in 1964, and Robert W. Floyd added the O(n) heap build that year.
The tree is the array itself, read level by level: index 0 is the root, and the children of index i sit at 2i + 1 and 2i + 2, as in a min heap. A max heap is the mirror image of a min heap: no child is larger than its parent.
First the sort builds the max heap. Then each extraction swaps the root, the largest value left, with the heap's last node, its final place. The heap shrinks by one, and the new root sifts down (the app's code calls this heapify): it trades places with its larger child until neither child is larger. The sorted part grows from the right, so ascending order needs a max heap; a min heap would sort in descending order.
For ten values, index 4 (n/2 − 1) is the last node with a child, and indices 5 to 9 are leaves: with no children, they already satisfy the heap condition. The build sifts down nodes 4, 3, 2, 1 and 0 in that order, so by a node's turn both subtrees below it are heaps.
Textbooks sift down with a swap per level. The app's heapify does it with a hole: when a child is larger, it copies the value into a temporary variable, so its node becomes a hole that may be overwritten. While the larger child is larger than this stored value, the child's value moves up into the hole, and the hole moves down. Then the stored value is pasted into the last hole: one write per level instead of a swap's three.
In pseudocode:
heapSort(a)
n = length of a
buildHeap(a, n)
for i from n - 1 down to 1
swap a[0] and a[i]
heapify(a, 0, i)
buildHeap(a, size)
for i from size / 2 - 1 down to 0
heapify(a, i, size)
heapify(a, i, size)
examined = a[i]
while i < size / 2
c = largestChild(a, i, size)
if examined >= a[c]
stop
a[i] = a[c]
i = c
a[i] = examined
largestChild(a, i, size)
l = 2 * i + 1
r = l + 1
if r < size and a[l] < a[r]
return r
return l
The names are the app's: heapSort, buildHeap, heapify and, shortened here, largestChild for its getLargestChildIndex. largestChild returns the left child unless the right one is inside the heap and larger, so a tie goes left. heapify copies a[i] into examined, the stored value. While i has a child (i < size / 2), it compares examined with the larger child c: if examined >= a[c], an equal child included, it stops; otherwise the child's value moves up and i moves down to c, the hole. Then examined fills the hole. / rounds down. buildHeap heapifies nodes size / 2 - 1 down to 0. In heapSort, the swap moves the root to a[i], the heap's last cell, and heapify(a, 0, i) repairs a[0..i - 1]. The app's code also shows a recursive heapify that swaps instead.
The player builds a max heap from the app's default array, 3, 10, 7, 8, 2, 6, 1, 4, 5, 9, sifting down nodes 4 to 0. A checked node turns yellow, then green if it satisfies the heap condition or red if a child is larger. The max heap is 10, 9, 7, 8, 3, 6, 1, 4, 5, 2.
Building from the bottom up costs O(n), as most nodes sit near the bottom and sift down few levels; the min heap page shows why.
Each extraction swaps the root with the last node of the heap; that node, now holding the maximum, leaves the tree for the sorted part, and the new root sifts down. The player extracts 10, 9 and 8, and each time the same value, 2, comes up to the root and sinks again. The heap is then 7, 5, 6, 4, 3, 2, 1, followed by 8, 9 and 10.
The player extracts 7, 6, 5, 4, 3 and 2 the same way. The last value, 1, is already in place, and the column becomes a sorted row again.
Because the heap shrinks from the right: each extraction frees its last cell, which in ascending order belongs to the largest value left, the root; a min heap would sort in descending order. The second player shows the first such swap at step 2.
No. A root swap can carry a value past an equal one; the example below shows how.
Because it makes n − 1 sift-downs, and a heap is a complete binary tree: n values fill only about log2 n levels (ten values fill four), so no sift-down can go deeper, whatever the input.
After the O(n) build, n − 1 sift-downs each descend at most log2 n levels, so heap sort takes O(n log n) even in the worst case. Each level costs two comparisons, child against child and stored value against the larger child: at worst about 2n log2 n. The default array takes 40: 12 to build and 28 to sort.
| Case | Comparisons, ten values | Time | Extra space |
|---|---|---|---|
| Best: all values equal | 24 | O(n) | O(1) |
| Best: distinct values | 31 | O(n log n) | O(1) |
| Average | 38.6 | O(n log n) | O(1) |
| Worst | 44 | O(n log n) | O(1) |
When all values are equal, every sift-down stops at its first check. Heap sort is not adaptive: sorted input is no faster. 1 to 10 in ascending order takes 41 comparisons, as the build lifts every large value to the top. Descending input is already a max heap, since each parent comes before its children and is larger. The build moves nothing, yet the extractions still make 26 comparisons: 35 in all.
Heap sort is in-place: the heap and the sorted part share the array, so the extra memory is the stored value and a few indices.
The value swapped to the root comes from the bottom of the heap, so it is usually small: here always 1, 2 or 3. In six of the example's eight sift-downs, it sinks to a leaf. Bottom-up heap sort therefore moves the hole straight down to a leaf, one comparison per level, and then lets the stored value climb back up: about n log2 n comparisons on average instead of 2n log2 n. GCC's and LLVM's C++ libraries, Python's heapq and the Linux kernel sift this way.
A stable sort keeps equal values in their original order. A root swap can carry a value past its equals. 2a, 2b, 1 is already a max heap, since 2a is not smaller than its larger child 2b. The first swap sends 2a to the end, behind 2b. 2b rises in the sift-down, and the second swap puts it back at index 1: 1, 2b, 2a.
Sorting pairs of value and original index makes it stable, at the cost of O(n) extra memory.
Heap sort is selection sort with a heap: each step still selects one value, the largest left, but in O(log n) instead of an O(n) scan. On selection sort's array 5, 2, 1, 4, 0, 6, 3, heap sort makes 20 comparisons and selection sort 21.
Quick sort is often two to three times faster than heap sort, as it reads memory in order; sift-down jumps from i to 2i + 1 and misses the cache on large arrays. But quick sort can degrade to O(n2), and merge sort, though stable, needs O(n) extra memory. Of the three, only heap sort guarantees O(n log n) in O(1) space, as the merge sort page shows.
The app shows the code in all three: an iterative heapify that fills the hole and a recursive one that swaps. The standard libraries differ.
Note
C++ has heap sort built in: std::make_heap builds a max heap, and std::sort_heap sorts it in place into ascending order.
Note
Python's heapq is a min heap, and the heapsort example in its documentation builds new lists: O(n) extra memory, and, as the docs say, not stable. Python 3.14 added max heap functions such as heapq.heapify_max.
Note
Java has no public heap sort method. PriorityQueue is a min heap: polling it once per value gives ascending order, but the queue is a copy that takes O(n) extra memory.
The full source code is on GitHub, in Python, Java and C++.
Heap sort suits:
O(n log n) guaranteed in O(1) extra memory, without recursion. The Linux kernel's sort() is a heap sort for this reason, and the app's info dialog names real-time data processing.std::sort does this in GCC and LLVM, and since Java 14 so does Arrays.sort for int, long, float and double arrays. Python's sort never uses heap sort.O(n + k log n).// in the app
In VisiGrab heap sort runs on the default, a random or your own array of ten values, with a step for every check, stored value, move, paste and root swap: 101 steps on the default array.
Random picks ten distinct values from 0 to 19. Custom opens a ten-cell dialog for values from 0 to 99, equal ones included, with buttons for an ascending fill, which takes 117 steps, or a descending one, which takes 87. Equal values show the tie rules at work.
Step forward and back through every check, red mark, store, move, paste, swap and shrink, each with its message. The last random or custom array comes back next time.
Two tabs. Info covers the two phases, what a max heap is, the characteristics (in-place with O(1) auxiliary space, unstable, not adaptive), O(n log n) in every case and a fit for real-time data processing. Details pairs an array fragment with its tree, then explains building the heap from the last non-leaf node and the sorting phase.
The heapSort, buildHeap, heapify and getLargestChildIndex methods in Java and heap_sort, build_heap, heapify and get_largest_child_index in Python and C++, plus a recursive heapify that swaps, with links to the full source on GitHub. After the last step, a hint points to the code.
Eight questions with an explanation for every answer, from why heap sort builds a max heap to how fast it runs on an array that is already sorted.
Bubble, selection, insertion, merge and quick sort each have a topic of their own, and the Heap topic builds a min heap step by step.
// build your own
Download VisiGrab and step through every sift-down and root swap, on the default array, a random one or an array of your own.
Heap sort is one of 30+ topics. See them all