Menu
Coddy logo textTech

Heap Sort

Last updated

Heap sort treats the array as a binary heap. First it builds a max-heap, so the largest element sits at the root (index 0). Then it repeatedly swaps the root with the last unsorted element - locking the maximum into place - and sifts the new root down to restore the heap property. Press play above to watch the heap build and the extractions.

Heap sort guarantees O(n log n) time like merge sort, but sorts in place with only O(1) extra space. It is not stable and tends to have worse cache behavior than quicksort, so it is often chosen when a guaranteed bound and constant memory both matter.

Time & space complexity

CaseComplexityNotes
Best caseO(n log n)Build + n extractions
Average caseO(n log n)Random order
Worst caseO(n log n)Guaranteed
SpaceO(1)In-place
StableNoSift-down reorders equal elements

Step by step

StepWhat happens
1Build a max-heap from the array (sift down from the last parent).
2Swap the root (maximum) with the last element of the heap.
3Shrink the heap by one - that last slot is now sorted.
4Sift the new root down to restore the max-heap property.
5Repeat until the heap has one element left.

Worked example

Sorting [3, 1, 6, 5, 2, 4]. The bar | marks the boundary between the shrinking heap and the sorted tail:

PassArrayAction
Build heap[6, 5, 4, 1, 2, 3]Sift down from the last parent to build the max-heap; 6 is now at the root.
1[5, 3, 4, 1, 2 | 6]Swap root 6 with the last slot, shrink the heap, and sift 3 down.
2[4, 3, 2, 1 | 5, 6]Swap root 5 out, then sift 2 down so 4 rises to the root.
3[3, 1, 2 | 4, 5, 6]Swap root 4 out, then sift 1 down so 3 rises to the root.
4[2, 1 | 3, 4, 5, 6]Swap root 3 out; 2 already satisfies the heap property.
5[1 | 2, 3, 4, 5, 6]Swap root 2 out; one element remains, so the array is sorted.

When to use heap sort

Use it whenAvoid it when
You need a guaranteed O(n log n) worst case with no risk of O(n²).You need a stable sort that preserves the order of equal keys.
Memory is tight - it sorts in place with only O(1) extra space.Cache performance matters and the data fits in memory - quicksort is usually faster.
You are already maintaining a heap (e.g. a priority queue) over the data.You want the fewest comparisons - merge sort and quicksort often do fewer in practice.
Untrusted input could trigger quicksort's worst case and you can't randomize.The data is nearly sorted - insertion sort runs in near-linear time on it.

Heap Sort code

A clean, runnable Heap Sort implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Heap Sort code in Python

Python
1def heap_sort(a):2    n = len(a)3    # Build a max-heap, deepest parent first4    for i in range(n // 2 - 1, -1, -1):5        sift_down(a, i, n)6    # Repeatedly move the max to the end and shrink the heap7    for end in range(n - 1, 0, -1):8        a[0], a[end] = a[end], a[0]9        sift_down(a, 0, end)10    return a11
12
13def sift_down(a, i, size):14    while True:15        largest = i16        left, right = 2 * i + 1, 2 * i + 217        if left < size and a[left] > a[largest]:18            largest = left19        if right < size and a[right] > a[largest]:20            largest = right21        if largest == i:22            return23        a[i], a[largest] = a[largest], a[i]24        i = largest25
26
27nums = [12, 11, 13, 5, 6, 7]28print("Before:", nums)29heap_sort(nums)30print("After: ", nums)
Run this code in the Python Playground

Heap Sort FAQ

What is the time complexity of heap sort?
Heap sort is O(n log n) in the best, average, and worst cases. Building the heap is O(n) and each of the n extractions costs O(log n). It uses O(1) extra space.
Is heap sort stable?
No. The sift-down operation can move equal elements past each other, so heap sort does not preserve the relative order of equal keys.
When should I use heap sort?
Use heap sort when you need a guaranteed O(n log n) worst case with only O(1) extra memory. It avoids quicksort’s O(n²) risk without merge sort’s O(n) buffer, at the cost of stability and cache performance.
What is the difference between heap sort and quicksort?
Both sort in place, but quicksort has an O(n²) worst case while heap sort guarantees O(n log n). In practice quicksort is usually faster because of better cache locality and fewer swaps, so heap sort is preferred mainly when the worst-case bound must be guaranteed.
How is heap sort related to a priority queue?
A binary heap is the standard implementation of a priority queue, and heap sort is essentially repeatedly popping the maximum from that queue. If you already keep your data in a heap, extracting elements one by one gives you a sorted order for free.
Does heap sort need a max-heap or a min-heap?
To sort in ascending order in place, use a max-heap: the largest element is swapped to the end on each pass, growing the sorted tail from the right. A min-heap would produce descending order in place, or ascending order if you extract into a separate array.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED