Heap Sort
- Ω( n log n )
- Θ( n log n )
- O( n log n )
- space O( 1 )
Heap sort turns the array into a binary max-heap and then empties it from the top. Each round swaps the largest value, which sits at index 0, into the last unsorted cell and repairs the heap in the shortened prefix. No recursion and no auxiliary buffer are needed, and the running time cannot degrade on unlucky input. The price is a memory access pattern that hops across the array rather than walking it.
- Comparisons count only element-against-element checks; loop and index checks are never counted.
- Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
- A swap counts once, as a swap. It is never also counted as a read or a write.
- Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.
How heap sort works
Start from 5, 2, 6, 1, 4, 3. The heap is built bottom-up, beginning at index 2, the last cell that has a child. The 6 there already beats its only child, the 3, so nothing moves. At index 1 the 2 has children 1 and 4, and the larger child wins: swap 1 and 4, giving [5, 4, 6, 1, 2, 3]. At index 0 the 5 has children 4 and 6, so it trades places with the 6 and the array becomes [6, 4, 5, 1, 2, 3]. Two swaps were enough to build a valid heap.
Extraction starts now. The root 6 swaps with the last cell, giving [3, 4, 5, 1, 2, 6], and the 3 is sifted down: it exchanges with the larger child 5 and the prefix reads [5, 4, 3, 1, 2], with the 6 fixed at the end. The next round sends the 5 to the back and sifts the displaced 2 below the 4, producing [4, 2, 3, 1, 5, 6]. After the 4 goes to index 3 the whole array reads [1, 2, 3, 4, 5, 6], and that is only the seventh swap of eleven.
The remaining four swaps work on a prefix that already holds the right values. The 1 that was just moved to the root sinks below the 3, the 3 goes to the back, the 1 swaps with the 2, and one last exchange puts that pair in order. The algorithm cannot see that the order is already correct, because it only knows the heap property, not the final order. The run ends with 14 comparisons and 11 swaps, which for six elements is no better than selection sort. The benefit of the heap shows up as n grows.
| Step | Change | Array after |
|---|---|---|
| 1 | Swap indexes 1 and 4 | 5 4 6 1 2 3 |
| 2 | Swap indexes 0 and 2 | 6 4 5 1 2 3 |
| 3 | Swap indexes 0 and 5 | 3 4 5 1 2 6 |
| 4 | Swap indexes 0 and 2 | 5 4 3 1 2 6 |
| 5 | Swap indexes 0 and 4 | 2 4 3 1 5 6 |
| 6 | Swap indexes 0 and 1 | 4 2 3 1 5 6 |
| 7 | Swap indexes 0 and 3 | 1 2 3 4 5 6 |
| 8 | Swap indexes 0 and 2 | 3 2 1 4 5 6 |
| 9 | Swap indexes 0 and 2 | 1 2 3 4 5 6 |
| 10 | Swap indexes 0 and 1 | 2 1 3 4 5 6 |
| 11 | Swap indexes 0 and 1 | 1 2 3 4 5 6 |
All 11 changes are shown.
Pseudocode
build a max-heap in a
for end = n - 1 down to 1
swap a[0], a[end]
sift a[0] down within a[0 .. end - 1]
sift down(root, size)
while root has a child inside size
child = larger of the children
if a[root] >= a[child]
stop
swap a[root], a[child]
root = child
Why these complexities
Building the heap bottom-up costs O(n), not O(n log n). Half of the cells are leaves and need no work, a quarter can sink at most one level, an eighth at most two, and so on, which sums to a linear amount of work. Each sift-down step spends two comparisons, one to pick the larger child and one against the parent, and one swap.
The extraction phase runs n - 1 rounds, and each sift-down descends at most log₂ n levels. That gives O(n log n) comparisons and swaps in the worst case, with roughly 2 n log₂ n comparisons. The best and average cases land at the same order for a reason: the value brought to the root came from the bottom of the heap, where values are small, so it nearly always sinks almost all the way down again. Already sorted input does not help. Eight sorted elements take 22 swaps here, while eight reversed elements take 16, but both stay within a small constant of each other.
Space is O(1) because the heap lives inside the array itself, with children of index i at 2i + 1 and 2i + 2, and sift-down is a loop, not a recursive call. The sorted region grows at the back as the heap shrinks at the front. Since every level of the descent touches an index twice as far from the root as the last one, successive reads are far apart in memory, which is why caches treat heap sort less kindly than the sequential scans of merge sort or quick sort.
Measured on this site
Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.
| Input | Comparisons | Writes | Swaps |
|---|---|---|---|
| Random | 213 | 0 | 125 |
| Already sorted | 231 | 0 | 146 |
| Reversed | 202 | 0 | 112 |
| Few distinct values | 208 | 0 | 111 |
When to use it
Use it when you need a guaranteed O(n log n) time with no extra memory, for example in embedded code or as the fallback of another sort. If average speed matters more, quick sort is usually faster.
Frequently asked questions
What is a heap?
A binary tree stored in the array in which every parent is at least as large as its children, so the root is the maximum.
Why is heap sort slower than quick sort in practice?
It jumps between distant positions of the array, which is hard on the cache, and it does more comparisons per element.
Is heap sort stable?
No. Moving the root to the end and rebuilding the heap reorders equal elements.
Why does the build phase start in the middle of the array?
In a heap stored in an array, the cells from index n/2 onwards have no children, so each is already a valid one-element heap. The loop therefore starts at the last cell that has a child, index floor(n / 2) - 1, which is 2 for six elements, and works backwards to the root. Starting from the front instead would force repeated repair work and lose the linear bound on construction.
Why does the trace keep swapping after the array looks sorted?
After seven of the eleven swaps the array already reads 1, 2, 3, 4, 5, 6, but heap sort has no way of checking this. It only knows that the prefix is a heap and that everything after it is final. It must keep shrinking the heap until one element is left, so every sorted input still pays the full extraction cost. Insertion sort and merge sort variants can stop early; heap sort cannot.
Background
J. W. J. Williams published heapsort in 1964 in Communications of the ACM, introducing the binary heap as the data structure that makes it work. In the same year Robert Floyd published an improved construction, the bottom-up build used in this implementation, which brings heap creation down from O(n log n) to O(n).
Heap sort was one of the first general comparison sorts to combine in-place operation with a guaranteed O(n log n) bound. That guarantee is why it survives as the safety net inside introsort, which switches to heap sort when quick sort recursion goes too deep. As a stand-alone sort it has been overtaken by quick sort and merge sort, which exploit cache behaviour better, and it is not stable.
References
- Williams, Algorithm 232: Heapsort, Communications of the ACM 7(6), 1964
- Floyd, Algorithm 245: Treesort 3, Communications of the ACM 7(12), 1964
- Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, chapter 6 (Heapsort)
- Knuth, The Art of Computer Programming, vol. 3, section 5.2.3 (Sorting by Selection)
Compare with
| Algorithm | Average time | Worst time |
|---|---|---|
| Selection Sort | Θ( n2 ) | O( n2 ) |
| Cycle Sort | Θ( n2 ) | O( n2 ) |
| Pancake Sort | Θ( n2 ) | O( n2 ) |
| Best time | Ω( n log n ) | good |
|---|---|---|
| Average time | Θ( n log n ) | good |
| Worst time | O( n log n ) | good |
| Worst space | O( 1 ) | good |
Properties
- Stable
- No
- In place
- Yes
- Adaptive
- No
- Comparison-based
- Yes