Imagine a knockout tournament where the champion always ends up at the very top of the bracket. Once you know who the champion is, you take them out, place them at the back of the line, and quickly shuffle the bracket so a new champion rises to the top. Repeat that until everyone has been placed, and the whole line is sorted.
That’s the idea behind heap sort. It’s a sorting algorithm with a reputation for being steady and dependable: it runs in O(n log n) time every time and needs almost no extra memory. In this guide, we’ll explain how the heap sort algorithm works, trace a full heap sort example by hand, write heap sort in Python, and break down its time complexity in plain English. We’ll also compare it with bubble sort, selection sort, insertion sort, merge sort and quick sort.
What Is Heap Sort?
Heap sort is a comparison-based sorting algorithm built on a data structure called a binary heap. You can think of it as an upgraded selection sort. Selection sort repeatedly scans the whole unsorted part to find the largest value, which is slow. Heap sort keeps the unsorted part organized as a heap, so the largest value is always sitting at the top, ready to grab.
The algorithm was invented by J. W. J. Williams in 1964, and the same paper introduced the binary heap itself. Robert W. Floyd published an improved version the same year, which made it possible to sort an array in place.
First, What Is a Heap?
A binary heap is a tree where every parent has at most two children, and the tree is filled in from left to right, level by level. Heap sort uses a max heap, which follows one simple rule: every parent is greater than or equal to its children. That means the biggest value always sits at the root.
Two things trip beginners up here, so let’s clear them up:
- A heap is not fully sorted. The rule only compares parents with their children, so two siblings can be in any order.
- You don’t need to build a real tree with pointers. A heap fits neatly inside a normal list, using simple index math.
For an item at index i (counting from 0):
- Left child:
2 * i + 1 - Right child:
2 * i + 2 - Parent:
(i - 1) // 2
So in the list [29, 10, 14, 37, 13], the root 29 has children 10 and 14, and 10 has children 37 and 13. This list is not yet a max heap, because 10 has a bigger child, 37. Fixing that is the first job of heap sort.
How Does Heap Sort Work?
Heap sort works in two phases:
- Build a max heap out of the list, so the largest value is at the root.
- Sort by repeatedly removing the root. Swap the root with the last item in the heap, shrink the heap by one (the old root is now in its final spot), then fix the heap so a new largest value rises to the top. Repeat until the heap is empty.
The fixing step has a name: heapify (also called sift down). It takes a value that’s out of place, compares it with its children, and swaps it with the larger child, again and again, until it settles where it belongs.
Heap Sort Step-by-Step Example
Let’s sort our usual list in ascending order:
[29, 10, 14, 37, 13]
Watch Heap Sort in Action
The tree shows the heap. The bars show the same values in the list, so you can see both views at once.
Phase 1: build the max heap
We start with the last parent (index 1, the value 10) and work backward to the root. The last parent in a list of n items is at index n // 2 - 1, because everything after it is a leaf with no children to fix.
10has children37and13. The bigger child (37) wins, so they swap. The list is [29, 37, 14, 10, 13].- Now the root,
29, has children37and14.37is bigger, so they swap, giving [37, 29, 14, 10, 13].29is bigger than its new children,10and13, so it stops there.
We now have a valid max heap, with the biggest value, 37, at the top.
Phase 2: sort by removing the root
- Swap the root
37with the last heap item13, then heapify the smaller heap. Result: [29, 13, 14, 10 | 37]. The bar marks the sorted part. - Swap
29with10, then heapify. Result: [14, 13, 10 | 29, 37]. - Swap
14with10, then heapify. Result: [13, 10 | 14, 29, 37]. - Swap
13with10. Result: [10 | 13, 14, 29, 37]. One item is left, so it's already in place.
Final answer: [10, 13, 14, 29, 37].
Heap Sort in Python
Here's a clean, in-place version. The heapify function uses a loop instead of recursion, which keeps the extra memory use constant:
def heapify(arr, n, i):
"""Sift the value at index i down until the heap rule holds.
n is the size of the heap (only look at arr[0:n])."""
while True:
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest == i: # already in the right place
return
arr[i], arr[largest] = arr[largest], arr[i]
i = largest # keep sifting down
def heap_sort(arr):
n = len(arr)
# Phase 1: build a max heap, starting from the last parent
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
# Phase 2: move the root to the end, shrink the heap, fix it
for end in range(n - 1, 0, -1):
arr[0], arr[end] = arr[end], arr[0]
heapify(arr, end, 0)
return arr
numbers = [29, 10, 14, 37, 13]
print(heap_sort(numbers))
# Output: [10, 13, 14, 29, 37]What each part does:
heapify(arr, n, i)pushes the value atidown the tree until it's no smaller than its children. Thentells it where the heap ends, so it never touches the sorted part.- The first loop builds the heap by heapifying every parent from
n // 2 - 1down to0. - The second loop swaps the root into its final spot at
end, then callsheapify(arr, end, 0). Passingendas the size is what shrinks the heap. - Everything happens inside the original list, so no second list is needed.
Heap Sort Time and Space Complexity
| Case | Time complexity |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n log n) |
| Extra space | O(1) |
One small footnote: some heap sort variants can finish in O(n) when every value in the list is equal, but for normal data you should treat it as O(n log n) no matter how the list starts out.
Where does O(n log n) come from?
- Building the heap takes O(n). It looks like it should be
O(n log n), but most items are near the bottom of the tree and only move a step or two. Add up the work level by level and it works out to aboutnsteps in total. - The sorting phase takes O(n log n). It removes the root
n - 1times, and each heapify can travel down at most the height of the tree, which is aboutlog nlevels.
Add them together and the sorting phase dominates, so the total is O(n log n). And because the heap is built inside the original list, heap sort needs only O(1) extra space, as long as heapify is written as a loop like ours.
Is Heap Sort Stable?
No. Heap sort is not stable, so equal values can end up in a different order than they started. The swaps between the root and the last item jump across the list, which scrambles the original order. Here's a tiny example, with two equal values labelled 3a and 3b:
[3a, 3b, 1] → [1, 3b, 3a]If you need equal items to keep their original order, use a stable sort such as merge sort or insertion sort.
Heap Sort vs. Quick Sort vs. Merge Sort
| Algorithm | Best | Average | Worst | Extra space | Stable? |
|---|---|---|---|---|---|
| Bubble sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick sort | O(n log n) | O(n log n) | O(n²) | O(log n) average | No |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
Heap sort is the only algorithm in this table that guarantees O(n log n) time and uses constant extra space. That's its superpower. The trade-offs:
- Versus quick sort: heap sort has no
O(n²)worst case, but a well-implemented quick sort is usually somewhat faster in practice, partly because heap sort hops around the list in ways that are less friendly to CPU caches. - Versus merge sort: both guarantee
O(n log n), but merge sort is stable and needs extraO(n)memory, while heap sort is in place and not stable.
Where Heap Sort Is Used in the Real World
You'll rarely call heap sort directly, but it shows up in smart places:
- As a safety net inside quick sort. Many real-world quick sort variants, such as the introsort commonly used for C++'s
std::sort, switch to heap sort if the recursion starts to go badly, which protects against theO(n²)worst case. - Priority queues. The heap data structure behind heap sort is the classic way to build a priority queue, which always hands you the biggest or smallest item first. Python's built-in
heapqmodule gives you a min-heap for exactly that. - Memory-tight or time-critical code. When you can't afford extra memory or a bad worst case, heap sort's guarantees are attractive.
Advantages and Disadvantages of Heap Sort
Advantages
- Guaranteed
O(n log n)time, with no bad inputs. - Sorts in place with
O(1)extra space. - Teaches you the heap, a data structure you'll use again for priority queues.
Disadvantages
- Not stable.
- Usually a bit slower than a good quick sort on ordinary data.
- Doesn't take advantage of lists that are already nearly sorted, unlike insertion sort.
- The index math can feel fiddly at first.
When Should You Use Heap Sort?
- You need a guaranteed worst case and can't spare extra memory.
- You're working in a memory-limited environment.
- You're learning heaps and priority queues, or preparing for interviews where they come up often.
Skip it when you need a stable sort, or when you just want fast everyday sorting. In normal projects, your language's built-in sort is almost always the right choice.
Common Mistakes to Avoid
- Getting the child indexes wrong. With a 0-based list, children are at
2*i + 1and2*i + 2, not2*iand2*i + 1. - Starting the build phase at the wrong index. Begin at
n // 2 - 1, the last parent, and work backward to0. - Forgetting to shrink the heap. Call
heapify(arr, end, 0), notheapify(arr, n, 0), or you'll pull sorted values back into the heap. - Using a min-heap for ascending order. A min-heap with this same process gives you a descending list. For ascending order, use a max-heap.
- Assuming it's stable. It isn't.
Try It Yourself
- Add a
print(arr)after each heapify call and compare the output with the animation above. - Change the comparisons so the code sorts in descending order.
- Count comparisons on a sorted list, a reversed list and a random list, and notice how similar the counts are.
- Sort a list of tuples like
(name, grade)by grade and watch equal grades change order.
Quick Recap
Heap sort builds a max heap so the biggest value sits at the top, then repeatedly swaps that value to the end of the list and repairs the heap. It runs in O(n log n) time in every case, sorts in place with O(1) extra space, and isn't stable. With heap sort, you've now covered the six classic sorts in this series: bubble, selection, insertion, merge, quick and heap sort.
Frequently Asked Questions
What is heap sort in simple words?
Heap sort arranges the list into a max heap so the largest value is on top, then repeatedly moves that largest value to the end and repairs the heap until the whole list is sorted.
What is the time complexity of heap sort?
O(n log n) in the best, average and worst cases. Building the heap takes O(n), and the sorting phase takes O(n log n).
Is heap sort stable?
No. Equal values can change their relative order during the swaps.
Is heap sort in-place?
Yes. It rearranges values inside the original list and needs only a constant amount of extra memory, as long as heapify is written as a loop.
What is the difference between a heap and heap sort?
A heap is a data structure where each parent is ordered relative to its children. Heap sort is an algorithm that uses a heap to sort a list.
Is heap sort better than quick sort?
It depends. Heap sort guarantees O(n log n) and uses less memory in the worst case, but quick sort is usually faster in practice. Many libraries combine both, falling back to heap sort if quick sort starts to struggle.
Does Python use heap sort?
No. Python's sorted() and list.sort() use Timsort. Python's heapq module offers heap operations for priority queues, but it isn't a sorting function.
Found this helpful? Run the Python code on lists of different sizes, then compare it with quick sort and merge sort. Seeing the numbers side by side is the fastest way to understand the trade-offs.
