Heap Sort
Heap sort uses a heap data structure to pull out the largest value one at a time and fill the array from the back.
At a Glance
- It is a sorting method based on the heap data structure, which is built on a complete binary tree.
- Complete binary tree = a binary tree filled from the top level down with no gaps, where the last level is filled from left to right. New nodes are also always added from the left, in order.
- Max heap = a heap where a parent is always greater than or equal to its children. So the root (the top) always holds the largest value. The opposite, where the parent is smaller, is a min heap.
- As an analogy, it is like a sports-day tournament: pick the winner, place them in the last spot on the podium, then have the remaining people compete again briefly to pick the next winner, and repeat.
- It is a comparison sort, which compares values with each other.
- It is an unstable sort. Because the root and the last element are swapped between far-apart positions, elements with equal values can change order.
- It only swaps positions inside the array, so it is an in-place sort.
Representing a Tree with an Array
A complete binary tree has no gaps, so it can be stored in an array level by level. For a node at index i, its family is calculated like this.
| Relation | Index |
|---|---|
| Left child | i * 2 + 1 |
| Right child | i * 2 + 2 |
| Parent | (i - 1) // 2 |
For example, the array [11, 9, 2, 7, 4] is this tree.
| Level | Nodes (index: value) |
|---|---|
| Level 1 (root) | 0: 11 |
| Level 2 | 1: 9, 2: 2 |
| Level 3 | 3: 7, 4: 4 (both are children of 9) |
How It Works
- Build a max heap from the whole array.
- The root of the current heap holds the largest value. Swap the root value with the last element of the heap, then shrink the heap size by one. (The value moved to the back is now in its final sorted position.)
- Rebuild a max heap from the shrunken heap, and if the heap size is greater than 1, repeat from step 2.
Heap sort is this process of sorting by pulling out the maximum value one at a time.
First, build a max heap from the example array [7, 4, 2, 9, 11]. Go backward from the last parent that has children (index 1) to the root (index 0), fixing each one.
| Step | Array state | Description |
|---|---|---|
| Start | [7, 4, 2, 9, 11] | Not a heap yet |
| Fix index 1 | [7, 11, 2, 9, 4] | Of 4's children 9 and 11, swap with the larger, 11 |
| Fix index 0 | [11, 7, 2, 9, 4] | Of 7's children 11 and 2, swap with the larger, 11 |
| Keep going down | [11, 9, 2, 7, 4] | Of the moved-down 7's children 9 and 4, swap with the larger, 9 |
| Max heap complete | [11, 9, 2, 7, 4] | Root 11 is the maximum |
Now send the maximum values to the back one by one. One round means "replace the root with the last node, then rebuild the max heap." The figure below shows a different example heap, [11, 5, 8, 3, 4], where the root 11 is replaced by the last node 4.

The 4 that moved up to the root is smaller than its children 5 and 8, so it swaps places with the larger child, 8, to rebuild the max heap.

Image source: gyoogle/tech-interview-for-developer Heap Sort
In the table below, the part after | is already sorted.
| Round | After swapping root and end | After rebuilding the max heap | Description |
|---|---|---|---|
| 1 | [4, 9, 2, 7 | 11] | [9, 7, 2, 4 | 11] | 11 goes to the back. Root 4 swaps with 9, then 7 |
| 2 | [4, 7, 2 | 9, 11] | [7, 4, 2 | 9, 11] | 9 goes to the back. Root 4 swaps with 7 |
| 3 | [2, 4 | 7, 9, 11] | [4, 2 | 7, 9, 11] | 7 goes to the back. Root 2 swaps with 4 |
| 4 | [2 | 4, 7, 9, 11] | [2 | 4, 7, 9, 11] | 4 goes to the back. Heap size becomes 1, done |
Result: [2, 4, 7, 9, 11]
In Pictures
The animation below builds a max heap from an array, then repeatedly sends the root (the maximum) to the end of the array and tidies up the remaining heap. The cells that turn black in the array at the top are the sorted part.

Image source: Wikimedia Commons (CC BY-SA 3.0, Swfung8)
Python Code
def heapify(array, n, i):
# 1. Find the position of the largest value among the parent (i) and its two children
p = i
l = i * 2 + 1
r = i * 2 + 2
if l < n and array[p] < array[l]: # if the left child is larger
p = l
if r < n and array[p] < array[r]: # if the right child is larger
p = r
# 2. If a child is larger, swap them and check again from the new position
if i != p:
array[p], array[i] = array[i], array[p]
heapify(array, n, p)
def heap_sort(array):
n = len(array)
# 3. Build a max heap: from the last parent with children (n//2 - 1) to the root (0)
for i in range(n // 2 - 1, -1, -1):
heapify(array, n, i)
# 4. Send the root (maximum) to the back, then rebuild the max heap from the remaining front part
for i in range(n - 1, 0, -1):
array[0], array[i] = array[i], array[0]
heapify(array, i, 0)
array = [230, 10, 60, 550, 40, 220, 20]
heap_sort(array)
print(array)
# Output: [10, 20, 40, 60, 220, 230, 550]heapifyis a function that "turns everything below nodeiinto a max heap."nis the length of the front part currently used as the heap; anything afternis already sorted and is left alone. It stores the position of the largest value among the parent, the left child, and the right child inp.- If there is a child larger than the parent (
i != p), the two are swapped. The value that moved down may still be smaller than its new children, so it keeps going down recursively, swapping parent and child until it is a max heap again. - This is the first
heapifyloop. See the explanation below. - This is the second
heapifyloop. See the explanation below.
First heapify: Turning a Plain Array into a Heap
- Its job is to arrange a plain array into a max heap.
- It goes from the lower parents upward, comparing parent and child nodes.
- Why loop from
n // 2 - 1down to 0? For indexi, the left child isi * 2 + 1and the right child isi * 2 + 2. So the last node with at least one child is atn // 2 - 1, and every node after that is a leaf with no children. A leaf is already a heap on its own, so it needs no fixing. Fixing from the lower parents first guarantees that, when you fix a higher parent, the subtrees under both of its children are already heaps.
Second heapify: Rebuilding the Heap After Removing One
- This rebuilds the max heap after the root (the maximum) is sent to the end and one element has been removed.
- Only the value that just moved up to the root is out of place, so it runs from the root (handling the extract operation that removes the maximum).
Example of Why It Is Unstable
If you label two equal 5s as 5a and 5b and sort [5a, 5b, 3], the root 5a goes to the back first, giving [3, 5b, 5a]. The 5a that was originally in front ended up behind, so it is not a stable sort.
Time and Space Complexity
| Case | Time complexity |
|---|---|
| Best | Ω(n log n) |
| Average | Θ(n log n) |
| Worst | O(n log n) |
- Building the initial max heap takes O(n), and after that, each of the n - 1 extractions of the maximum walks down the height of the tree (log n) to fix things, so the total is O(n log n). It stays about the same regardless of the shape of the input. (Only in the special case where all values are equal do no swaps happen, giving O(n).)
- Space complexity: it only swaps positions inside the array, so extra memory is O(1). However, if
heapifyis written recursively as in the code above, the call stack grows by O(log n); rewriting it as a loop makes it O(1).
Where Heap Sort Is Used
Quick sort and merge sort perform well, so heap sort itself is not used very often. However, the heap data structure is widely used, and heap sort is the concept that comes along with it.
When Heap Sort Is Useful
- Finding the largest or smallest value: it is the root of a max heap or min heap, so a single heap build is enough to get it.
- Sorting elements that are at most k positions away: if every element is within k positions of its sorted position, a min heap of size k + 1 can sort it in O(n log k). This is an improvement over insertion sort (O(nk)).
import heapq
def sort_k_sorted(arr, k):
# 1. Build a min heap from the first k+1 elements (the smallest value is guaranteed to be in here)
heap = arr[:k + 1]
heapq.heapify(heap)
result = []
# 2. Each time you take one out, put the next value in → heap size stays at most k+1
for x in arr[k + 1:]:
result.append(heapq.heappushpop(heap, x))
# 3. Take out the remaining values in order
while heap:
result.append(heapq.heappop(heap))
return result
print(sort_k_sorted([2, 1, 4, 3, 6, 5, 8, 7], 1))
# Output: [1, 2, 3, 4, 5, 6, 7, 8]- The correct position of the first element is index 0, and that value was originally somewhere in cells 0 to k. So putting only the first k + 1 elements into the heap is enough to find the smallest value.
heappushpoppushes a new value and pops the smallest one. The heap size stays small at k + 1, so each call is O(log k).- Once the input runs out, the values left in the heap are popped in ascending order and appended.
Summary
| Concept | Plain-language summary |
|---|---|
| Heap sort | Pick the winner, put them at the back, and pick a new winner from the rest, again and again |
| Complete binary tree | A tree filled from the top level down, with the last level filled from the left, no gaps |
| Max heap | A pyramid where a parent is always larger than its children. The top is the maximum |
| heapify | Restores the heap rule by swapping an out-of-place value with its children and moving it down |
| Unstable sort | Equal values can change their original order |
