Heapsort sorts a list in two phases. First, it rearranges the values into a max-heap, a binary tree in which every parent is at least as large as its children. Then it repeatedly moves the largest remaining value to the end of the list and restores the heap on the part that is left. The method runs in O(n log n) time in the worst and average cases, and it needs only a constant amount of extra memory.
What a max-heap looks like in an array
A binary heap is usually stored in an array rather than with pointers. Its shape is a complete binary tree, so the array can be filled from left to right, one level at a time. With zero-based indexing, the children of the item at index i sit at 2i + 1 and 2i + 2, and its parent sits at floor((i - 1) / 2).
In a max-heap, every parent is greater than or equal to its children. The array [10, 5, 3, 4, 1] is a valid max-heap. The 10 at index 0 is the root. Its children, 5 and 3, sit at indexes 1 and 2. The 5 has two children, 4 and 1, at indexes 3 and 4. The 3 has no children, because indexes 5 and 6 are past the end of the array.
If the term is new to you, what is a heap data structure covers the idea in more depth. The short version is that a heap only guarantees the order between a parent and its children, not across the whole tree.
Heapify: restoring order at one node
The core tool is called heapify, or sift-down. It starts at one index whose two subtrees are already heaps, but whose value may be smaller than one of its children. Heapify swaps that value with its larger child and repeats the step further down the tree until the value is at least as large as its children, or it reaches a leaf.
Heapify makes at most one swap per level of the tree. A tree with n items has about log2 n levels, so one heapify call takes O(log n) time. The same logic can be written recursively, a pattern common in recursive algorithm examples, but a loop is common in practice because it avoids the overhead of function calls.
Readers often ask, “Is heapsort just heapify?” The short answer is no. Heapify is one step inside the method, and that difference is covered in its own article.
Step 1: build the max-heap
The array starts unordered, so the first phase arranges it into a max-heap. Leaves are already one-item heaps, so the work starts at the last parent, index floor(n / 2) - 1, and moves back toward the root. Each of those indexes gets one heapify call.
Working from the bottom up means each subtree is already a heap before its parent is handled. This phase takes O(n) time in total, not O(n log n). Most nodes sit near the bottom of the tree, where heapify’s paths are short, so the total stays linear. Inserting the values one at a time would cost O(n log n), which is why the bottom-up method is the standard choice.
Step 2: move the largest value to the end
Once the array is a max-heap, the largest value sits at index 0. The second phase repeats three steps until only one item is left in the heap:
- Swap the root with the last item still in the heap. The largest value is now in its final position at the end.
- Shrink the heap by one, so the item just moved is no longer part of it.
- Heapify the new root, which restores the max-heap order on what remains.
Each removal costs O(log n). With n items there are n - 1 removals, so this phase takes O(n log n) time. Added to the build phase, the total is still O(n log n).
A worked example
Take the list [4, 10, 3, 5, 1]. The table shows the heap part and the sorted part after each stage. The sorted part is the tail of the array, and it fills in from the end.
| Stage | Heap part | Sorted part |
|---|---|---|
| Start (unordered) | 4, 10, 3, 5, 1 | none |
| After the build phase | 10, 5, 3, 4, 1 | none |
| Swap 10 out, then heapify | 5, 4, 3, 1 | 10 |
| Swap 5 out, then heapify | 4, 1, 3 | 5, 10 |
| Swap 4 out, then heapify | 3, 1 | 4, 5, 10 |
| Swap 3 out, then heapify | 1 | 3, 4, 5, 10 |
The final array is 1, 3, 4, 5, 10.
Python code
Here is a short version in Python. It sorts the list in place, in ascending order.
def heapsort(a):
n = len(a)
# Phase 1: build a max-heap, starting from the last parent
for i in range(n // 2 - 1, -1, -1):
sift_down(a, i, n)
# Phase 2: move the largest value to the end and restore the heap
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)
def sift_down(a, i, size):
while True:
left = 2 * i + 1
right = left + 1
largest = i
if left < size and a[left] > a[largest]:
largest = left
if right < size and a[right] > a[largest]:
largest = right
if largest == i:
return
a[i], a[largest] = a[largest], a[i]
i = largest
After values = [4, 10, 3, 5, 1] and heapsort(values), the list holds [1, 3, 4, 5, 10].
Speed, memory and stability
Each operation on a heap has its own cost, so the question of what is the time complexity of a heap depends on which operation you mean. For heapsort as a whole, three properties matter when you compare it with other sorts:
- Time: O(n log n) in the worst and average cases.
- Extra memory: O(1). The sort works inside the array, so it is an in-place algorithm.
- Stability: heapsort is not stable, so equal values can change their order. Take [2a, 2b, 1], where the letters show the original order of the two 2s. After heapsort the list is [1, 2b, 2a], and the two 2s are reversed. Stability is one of the first things to check when you ask which sorting algorithms are stable.
Heapsort also doesn’t gain much from input that is already partly sorted, unlike insertion sort, because its main steps run much the same way whatever the input looks like.
Heapsort in practice
Heapsort is correct and has a guaranteed bound, but it is often slower than a well-written quicksort on ordinary hardware. Its memory accesses jump around the array, which uses the CPU cache poorly. Quicksort’s accesses are usually more predictable, which is a large part of why it tends to be faster on real data.
One of heapsort’s useful practical roles is as a backup. Introsort is a hybrid method used in some standard library sorting routines. It starts with quicksort and switches to heapsort if the recursion goes too deep. That keeps the worst case at O(n log n) while keeping quicksort’s speed on most inputs.
When heapsort is a good choice
Heapsort fits when you need a guaranteed O(n log n) bound, only a small amount of extra memory, and no stability requirement. There is no single answer to what is the most efficient sorting algorithm, because the answer depends on the data and on the limits you have.
The heap idea matters beyond sorting. Heaps are a common way to build a priority queue, which sits behind job queues, cpu scheduling algorithms, and many shortest-path searches. Dijkstra’s algorithm, for example, often uses a heap, and it is compared with another method in dijkstra algorithm vs bellman ford.
For the notation used in this article, see the guide to big o data structures.
Where the method came from
J. W. J. Williams described heapsort in 1964, and the same paper introduced the binary heap. Later that year, Robert W. Floyd published a faster method for building the initial heap. That method, which makes the build phase linear, is the one described above.