AlgoViz

Heap sort

medium 18 min

Heap sort turns the array into a max-heap in O(n), then repeatedly swaps the root (the maximum) to the end and sifts the new root down in O(log n).

Video lesson · Chapter 1 of 6

Who gets the final slot?

0:00 / 5:16

Heapsort — The heaviest gem goes last

1:26Reel

Read caption

Lux uses the same five gem slots as a max-heap and an expanding sorted suffix. Crown the maximum. Park it. Repair the heap.

How it works

Step through the idea, or press Play.

Step 1 of 3

Build a max-heap. Sift down every parent, from the last one back to the root, so the largest value ends up at index 0

Understand it

Start here

What heap sort is

Heap sort is a comparison sort built on a binary max-heap. It first rearranges the array so that the largest value sits at the front, then repeatedly moves that maximum to the back of the array and repairs the heap for the values that are left. Think of a tournament: the winner takes the last open place, a short replay crowns the next winner, and so on until every place is filled.

  • Heapify

    Turn the whole array into a max-heap, bottom up, in O(n)O(n).

  • Extract

    The root is the maximum. Swap it with the last heap slot.

  • Adjust

    Sift the new root down to restore the heap in O(log⁡n)O(\log n).

  • Place

    The swapped-out maximum is in its final slot. The sorted part grows by one.

Foundations

A max-heap lives inside the array

A binary max-heap is a complete binary tree in which every parent is greater than or equal to its children, so the root is the maximum. Because the tree is complete, it packs into an array level by level with no gaps and no pointers. See heap properties for the full story.

Index arithmetic (0-based)

left(i)=2i+1,right(i)=2i+2,parent(i)=⌊i−12⌋\text{left}(i) = 2i + 1, \qquad \text{right}(i) = 2i + 2, \qquad \text{parent}(i) = \left\lfloor \frac{i - 1}{2} \right\rfloor
Heap property: A[parent(i)]≥A[i]A[\text{parent}(i)] \ge A[i] for every i≥1i \ge 1. The last parent is at ⌊n/2⌋−1\lfloor n/2 \rfloor - 1; everything after it is a leaf.

The heap [10, 5, 3, 4, 1]

IndexValueParentLeft childRight child
010 (root)none2⋅0+1=12 \cdot 0 + 1 = 1: 52⋅0+2=22 \cdot 0 + 2 = 2: 3
15⌊0/2⌋=0\lfloor 0/2 \rfloor = 0: 102⋅1+1=32 \cdot 1 + 1 = 3: 42⋅1+2=42 \cdot 1 + 2 = 4: 1
230: 105: out of range6: out of range
34⌊2/2⌋=1\lfloor 2/2 \rfloor = 1: 5leafleaf
41⌊3/2⌋=1\lfloor 3/2 \rfloor = 1: 5leafleaf
Every parent beats its children: 10≥510 \ge 5, 10≥310 \ge 3, 5≥45 \ge 4, 5≥15 \ge 1. As a tree: root 10, children 5 and 3, and 4 and 1 under 5.

Core routine

Sift down (heapify)

heapify(arr, n, i): sink arr[i] to its place

Pick the biggest of the node and its two children. If the node already wins, stop. Otherwise swap with the bigger child and follow the value down. It assumes both child subtrees are already heaps. More in heapify.
Python
def heapify(arr, n, i):    """Sift arr[i] down inside the heap arr[0..n-1]."""    largest = i    left, right = 2 * i + 1, 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:        arr[i], arr[largest] = arr[largest], arr[i]        heapify(arr, n, largest)a = [4, 10, 3, 5, 1]heapify(a, 5, 1)    # 10 already beats 5 and 1: no changeheapify(a, 5, 0)    # 4 sinks: swap with 10, then with 5print(a)            # [10, 5, 3, 4, 1]
Recursive heapify. Each call moves down one level, so it costs at most the height of the node: O(log⁡n)O(\log n).
Edit and run it in your browser

Phase 1

Build the max-heap bottom up

Leaves are already one-node heaps. So start at the last parent ⌊n/2⌋−1\lfloor n/2 \rfloor - 1 and heapify each node, moving left to the root. When a node is processed, both of its subtrees are heaps already, which is exactly what heapify needs.

build_max_heap

Going backwards matters. Going forwards from the root, a node would be sifted before its subtrees were heaps.

Worked example: [4, 10, 3, 5, 1]

  1. 1

    Start

    n=5n = 5, last parent ⌊5/2⌋−1=1\lfloor 5/2 \rfloor - 1 = 1. Slots 2, 3 and 4 are leaves. As a tree: root 4, children 10 and 3, then 5 and 1 under 10.

  2. 2

    i = 1 (value 10)

    Children 5 and 1. 10>510 > 5 and 10>110 > 1: already a heap, no swap.

  3. 3

    i = 0 (value 4)

    Children 10 and 3. 10>410 > 4: swap, giving [10, 4, 3, 5, 1].

  4. 4

    Follow 4 to slot 1

    Children 5 and 1. 5>45 > 4: swap, giving [10, 5, 3, 4, 1]. Slot 3 is a leaf, so stop.

  5. 5

    Done

    Max-heap [10, 5, 3, 4, 1] after 6 comparisons and 2 swaps.

Deep dive

Why building the heap is O(n)

Each heapify costs at most the height hh of its node, and at most ⌈n/2h+1⌉\lceil n / 2^{h+1} \rceil nodes have height hh. Half the nodes are leaves (height 0), a quarter have height 1, and only the root has height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor. Expensive nodes are rare.

Total work of build-heap

T(n)≤∑h=0⌊log⁡2n⌋⌈n2h+1⌉c h  ≤  c n∑h=0∞h2h  =  c n⋅2  =  O(n)T(n) \le \sum_{h=0}^{\lfloor \log_2 n \rfloor} \left\lceil \frac{n}{2^{h+1}} \right\rceil c\,h \;\le\; c\,n \sum_{h=0}^{\infty} \frac{h}{2^{h}} \;=\; c\,n \cdot 2 \;=\; O(n)
The ceiling adds at most one node per level, which is only O(log⁡2n)O(\log^2 n) extra. The 12\frac{1}{2} in n2h+1\frac{n}{2^{h+1}} is absorbed into the constant.

The series that converges

∑h=0∞h xh=x(1−x)2⇒∑h=0∞h2h=1/2(1/2)2=2\sum_{h=0}^{\infty} h\,x^{h} = \frac{x}{(1 - x)^2} \quad\Rightarrow\quad \sum_{h=0}^{\infty} \frac{h}{2^h} = \frac{1/2}{(1/2)^2} = 2
Differentiate the geometric series ∑xh=11−x\sum x^h = \frac{1}{1-x} and multiply by xx. For a perfect tree the exact sum of heights is n−log⁡2(n+1)n - \log_2(n + 1): 11 swaps at most for 15 nodes.
nMost swaps, bottom-up buildInserting one by one (sift up)nlog⁡2nn \log_2 n
7410about 20
151134about 59
1,0231,0138,194about 10,229
1,000,000999,993about 18 millionabout 19.9 million
Sifting down pays each node's height, which is small for most nodes. Inserting and sifting up pays each node's depth, which is large for most nodes: Θ(nlog⁡n)\Theta(n \log n).

Phase 2

Extract the max, n - 1 times

Now arr[0] is the largest value. Swap it with the last slot of the heap: the maximum lands in its final position. Shrink the heap by one, so that slot is never touched again, and sift the new root down. The heap shrinks from the right while the sorted part grows from the right.

ExtractionSwapAfter sifting the root downHeap | sorted
start10, 5, 3, 4, 1 |
110 ↔ 11 sinks below 5, then below 45, 4, 3, 1 | 10
25 ↔ 11 sinks below 44, 1, 3 | 5, 10
34 ↔ 33 already beats 13, 1 | 4, 5, 10
43 ↔ 1heap of one1 | 3, 4, 5, 10
Four extractions for five values: the last value is in place automatically. Whole sort: 12 comparisons and 9 swaps.

The full algorithm

The heap size passed to heapify is end, not n, so the sorted suffix stays out of the heap.

Put together

The complete algorithm

Python
def heapify(arr, n, i):    largest = i    left, right = 2 * i + 1, 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:        arr[i], arr[largest] = arr[largest], arr[i]        heapify(arr, n, largest)def heap_sort(arr):    n = len(arr)    for i in range(n // 2 - 1, -1, -1):     # phase 1: build        heapify(arr, n, i)    for end in range(n - 1, 0, -1):         # phase 2: extract        arr[0], arr[end] = arr[end], arr[0]        heapify(arr, end, 0)    return arrprint(heap_sort([4, 10, 3, 5, 1]))          # [1, 3, 4, 5, 10]print(heap_sort([12, 11, 13, 5, 6, 7]))     # [5, 6, 7, 11, 12, 13]
In place, no extra arrays. Run it to see the result.
Edit and run it in your browser
HEAP: the four beats
  1. 1HeapifyBuild the max-heap once
  2. 2ExtractTake the root, the maximum
  3. 3AdjustSift the new root down
  4. 4PlaceMax sits at the end; repeat
Repeat: back to Heapify

Heapify happens once; Extract, Adjust and Place loop $n - 1$ times.

Complexity

O(n log n) in every case

Total time

T(n)=O(n)⏟build+∑k=2nO(log⁡k)⏟sift a heap of k=O(n)+O(log⁡n!)=O(nlog⁡n)T(n) = \underbrace{O(n)}_{\text{build}} + \sum_{k=2}^{n} \underbrace{O(\log k)}_{\text{sift a heap of } k} = O(n) + O(\log n!) = O(n \log n)
By Stirling, log⁡2n!=nlog⁡2n−1.44n+O(log⁡n)\log_2 n! = n \log_2 n - 1.44n + O(\log n). The extraction phase dominates. Each sift makes up to 2 comparisons per level, so the worst case is about 2nlog⁡2n2n \log_2 n comparisons.
CaseTimeWhy
BestO(nlog⁡n)O(n \log n)Each extraction brings a small leaf value to the root, and it usually sinks most of the way back down
AverageO(nlog⁡n)O(n \log n)Same work for any order of distinct values
WorstO(nlog⁡n)O(n \log n)No bad pivot, no bad input: the heap is always balanced
SpaceO(1)O(1) extraOnly swaps inside the array; iterative heapify needs no stack
One exception: if every value is equal, no sift ever moves, so the sort finishes in O(n)O(n). For distinct values the lower bound is Ω(nlog⁡n)\Omega(n \log n) even in the best case.

Properties

In place, not stable, not adaptive

  • In place

    O(1)O(1) extra memory. The heap and the sorted part share the one array.

  • Not stable

    Long-distance swaps can jump an equal value over its twin, so equal keys may change order.

  • Not adaptive

    Sorted, reversed and random inputs all cost about the same. Nearly sorted data gets no discount.

  • Comparison based

    Only compares values, so the Ω(nlog⁡n)\Omega(n \log n) lower bound applies. Heap sort meets it.

Python
def heap_sort_by_key(arr):    n = len(arr)    def heapify(size, i):        largest, l, r = i, 2 * i + 1, 2 * i + 2        if l < size and arr[l][0] > arr[largest][0]: largest = l        if r < size and arr[r][0] > arr[largest][0]: largest = r        if largest != i:            arr[i], arr[largest] = arr[largest], arr[i]            heapify(size, largest)    for i in range(n // 2 - 1, -1, -1): heapify(n, i)    for end in range(n - 1, 0, -1):        arr[0], arr[end] = arr[end], arr[0]        heapify(end, 0)    return arrprint(heap_sort_by_key([(3, "a"), (3, "b"), (1, "c")]))# [(1, 'c'), (3, 'b'), (3, 'a')]: 3a started first but ends last
Instability in three values: the two 3s come out in reverse order.
Edit and run it in your browser

Head to head

Heap sort vs quick sort vs merge sort

PropertyHeap sortQuick sortMerge sort
Best timeO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)
Worst timeO(nlog⁡n)O(n \log n)O(n2)O(n^2)O(nlog⁡n)O(n \log n)
Extra spaceO(1)O(1)O(log⁡n)O(\log n) stackO(n)O(n)
StableNoNoYes
In placeYesYesNo
Cache behaviourPoor: jumps from ii to 2i+12i + 1Excellent: sequential scansGood: sequential merges
In practiceSafety net, top-kFastest on averageStable sorts, linked lists, external data
Heap sort is the only one of the three that is both in place and O(nlog⁡n)O(n \log n) in the worst case.

Which O(n log n) sort?

Libraries often combine them: introsort runs quick sort and switches to heap sort if the recursion gets too deep.

In practice

Where heap sort is used

Introsort: quick sort with a heap sort safety net

C++ std::sort and .NET's Array.Sort work this way: quick sort's speed, heap sort's worst-case guarantee, insertion sort for tiny ranges.

Good for

  • A guaranteed O(nlog⁡n)O(n \log n) with no bad inputs.
  • Memory-constrained code: O(1)O(1) extra space.
  • Finding the kk largest or smallest values: build once, extract kk times.
  • Real-time and embedded systems where the worst case matters.
  • Learning priority queues: the same heapify and sift-down routines.

Avoid when

  • Stability is required: use merge sort or Timsort.
  • Data is nearly sorted: insertion sort or Timsort is much faster.
  • Cache performance is critical on large arrays.
  • Average-case speed matters most: quick sort is usually faster.
  • Top k

    Stop after kk extractions: O(n+klog⁡n)O(n + k \log n), or keep a size-kk min-heap for O(nlog⁡k)O(n \log k) on a stream.

  • k-sorted data

    Each value is at most kk slots from home: a min-heap of size k+1k + 1 sorts it in O(nlog⁡k)O(n \log k).

  • Merging k lists

    A heap of the kk list heads picks the next smallest in O(log⁡k)O(\log k).

Recap

Key takeaways

Key points

  • Heap sort has two phases: build a max-heap bottom up, then n−1n - 1 times swap the root to the end and sift down.
  • In a 0-based array: children at 2i+12i + 1 and 2i+22i + 2, parent at ⌊(i−1)/2⌋\lfloor (i - 1)/2 \rfloor, last parent at ⌊n/2⌋−1\lfloor n/2 \rfloor - 1.
  • Build-heap is O(n)O(n) because ∑hn2h+1h≤n\sum_h \frac{n}{2^{h+1}} h \le n; the O(nlog⁡n)O(n \log n) comes from the extractions.
  • O(nlog⁡n)O(n \log n) best, average and worst for distinct values; O(1)O(1) extra space.
  • Not stable and not adaptive; slower than quick sort in practice because of poor cache locality.
  • Used as introsort's fallback and for top-k problems.

Sources