COMPARISON SORTS
Heap Sort, visualised
Heap sort rearranges the array into a max-heap (a binary tree where each parent is at least as large as its children) and repeatedly moves the maximum at the root to the end.
Run Heap Sort in the visualizer →
Opens the Sorting Cinema visualizer with 16 elements in English.
How it works
- Treat the array as a binary tree and sift down from the lowest parent upward to build a max-heap.
- Swap the root (the maximum) with the last unsorted element; that position is now fixed.
- Sift the new root down to restore the max-heap on the remaining part.
- Repeat until one unsorted element remains.
Complexity and stability
- Best
- O(n log n)
- Average
- O(n log n)
- Worst
- O(n log n)
- Extra space
- O(1)
- Stability
- Usually unstable
Building the heap plus n extractions gives O(n log n) in the best, average and worst cases. It sorts in place, so extra space is O(1).
Source of facts: Complexity follows the learning guide's comparison table and text, and this app's implementation.
Trace on a small array
The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.
| # | Operation | Array after |
|---|---|---|
| 1 | Compare [1]=2 and [3]=1 | [5, 2, 4, 1, 3] |
| 2 | Compare [1]=2 and [4]=3 | [5, 2, 4, 1, 3] |
| 3 | Swap [1]=2 and [4]=3 | [5, 3, 4, 1, 2] |
| 4 | Compare [0]=5 and [1]=3 | [5, 3, 4, 1, 2] |
| 5 | Compare [0]=5 and [2]=4 | [5, 3, 4, 1, 2] |
| 6 | Swap [0]=5 and [4]=2 | [2, 3, 4, 1, 5] |
| 7 | Compare [0]=2 and [1]=3 | [2, 3, 4, 1, 5] |
| 8 | Compare [1]=3 and [2]=4 | [2, 3, 4, 1, 5] |
…and so on. In this trace, 16 compare / swap / write operations in total produce [1, 2, 3, 4, 5].
Suitable inputs and caveats
- Its running time depends little on input order and it needs little extra space.
- In the visualisation, after each root-to-end swap you can watch a value travel down the tree.
- It swaps distant elements, so it is usually unstable.
FAQ
What is a heap?
A binary tree arranged so that each parent is at least as large as its children (a max-heap). In an array, the children of position i are 2i+1 and 2i+2.
Is heap sort stable?
Usually not. Swaps such as root-to-end can change the original order of equal values.