Heap Sort

How heap sort builds a max-heap and repeatedly moves the largest item to the end, why it is O(n log n) in place, and what interviewers ask about it.

14 minLesson 4 of 7
On this page
  1. What a heap needs to provide
  2. How heap sort works
  3. Code
  4. Time and space
  5. Variants and alternatives
  6. Pitfalls
  7. In the interview
  8. What to practise next

Heap sort sorts an array in place by first arranging it as a max-heap and then repeatedly moving the largest item to the end. It runs in O(n log n) time on every input and uses O(1) extra memory. You reach for it when you need both of those guarantees together, which merge sort (extra memory) and quicksort (bad worst case) cannot give.

It is a faster version of selection sort. Selection sort finds the largest remaining item by scanning all of them, which costs O(n) per item and O(n²) overall. A heap keeps the largest item at the front and restores that property in O(log n) steps after each removal.

What a heap needs to provide

A max-heap is a binary tree in which every parent is at least as large as its children, so the largest item is always at the root. The full treatment is in Heaps and Priority Queues. Heap sort uses three facts from it.

  • The tree is stored in a plain array, level by level. The children of index i are at 2i + 1 and 2i + 2, so no pointers are needed.
  • The root, a[0], is the largest item.
  • Sift down repairs a heap whose root is out of place. It swaps the item with its larger child, again and again, until the item is at least as large as both of its children. The tree has about log₂ n levels, so a sift down makes at most log₂ n swaps.
9 8 5 1 3 2 index 0 9 8 5 1 3 2 0 1 2 3 4 5 array tree
One max-heap, drawn as a tree and stored as an array. The children of index 1 are at indexes 3 and 4.

How heap sort works

The algorithm has two phases. In the first, it turns the whole array into a max-heap in place. In the second, it repeats the following until one item is left: swap the root, which is the largest item, with the last item of the heap; that position is now final, so the heap shrinks by one; then sift the new root down to repair the heap. The array is therefore split into a shrinking heap at the front and a growing sorted section at the back.

Phase 1: build the heap

Every item in the second half of the array is a leaf, and a leaf is already a heap of one item. So the build starts at the last parent, index n/2 − 1, and sifts down each item on the way back to index 0. When the loop reaches an item, both of its subtrees are already heaps, so sifting it down makes its whole subtree a heap.

Build a max-heap from [3, 8, 5, 1, 9, 2]Use the arrows or ← → keys
for i from n/2 - 1 down to 0: siftDown(a, i, n)for end from n - 1 down to 1:  swap a[0] and a[end]  siftDown(a, 0, end) siftDown(a, i, size):  while i has a child below size:    c = the bigger child of i    if a[c] <= a[i]: stop    swap a[i] and a[c]; i = c
  1. a
    03
    18
    25i
    31
    49
    52
    385192

    1Indexes 3, 4 and 5 have no children, so each is already a heap of one item. The last parent is at index 6/2 − 1 = 2.

  2. a
    03
    18
    25i
    31
    49
    52
    385192

    2Index 2 holds 5, and its only child, 2, is smaller, so nothing moves.

  3. a
    03
    19i
    25
    31
    48
    52
    395182

    3Index 1 holds 8, and its bigger child, 9, is larger, so they swap. The 8 is now on a leaf and stops.

  4. a
    09i
    13
    25
    31
    48
    52
    935182

    4Index 0 holds 3, and its bigger child, 9, is larger, so they swap and 9 becomes the root.

  5. a
    09
    18i
    25
    31
    43
    52
    985132

    5The 3 keeps sifting down. At index 1 its bigger child is 8, so they swap, and the 3 ends on a leaf.

  6. a
    09
    18
    25
    31
    43
    52
    985132
    swaps
    3

    6Every parent is now at least as large as its children, with 9 at the root. Building the heap took 3 swaps.

1 / 6

Phase 2: move the maximum to the end

In the next trace, the faded nodes and marked cells are the sorted section, which is no longer part of the heap.

Sort the heap [9, 8, 5, 1, 3, 2]Use the arrows or ← → keys
for i from n/2 - 1 down to 0: siftDown(a, i, n)for end from n - 1 down to 1:  swap a[0] and a[end]  siftDown(a, 0, end) siftDown(a, i, size):  while i has a child below size:    c = the bigger child of i    if a[c] <= a[i]: stop    swap a[i] and a[c]; i = c
  1. a
    09
    18
    25
    31
    43
    52end
    985132
    heap size
    6

    1The heap covers all 6 items, and its root, 9, belongs in the last slot.

  2. a
    02
    18
    25
    31
    43
    59
    285139
    heap size
    5

    2Swap 9 with the last heap item, 2. The 9 is now in its final place, the heap shrinks to 5 items, and its root, 2, is out of place.

  3. a
    08
    12
    25
    31
    43
    59
    825139
    heap size
    5

    3Sift the 2 down. Its bigger child is 8, so they swap.

  4. a
    08
    13
    25
    31
    42
    59
    835129
    heap size
    5

    4At index 1, the children of 2 are 1 and 3, so the 2 swaps with the 3. The heap is repaired with 8 on top.

  5. a
    02
    13
    25
    31
    48
    59
    235189
    heap size
    4

    5Swap the root, 8, into slot 4. The heap now has 4 items.

  6. a
    05
    13
    22
    31
    48
    59
    532189
    heap size
    4

    6Sift the 2 down by swapping it with its bigger child, 5. Index 2 has no children inside the heap, so it stops.

  7. a
    01
    13
    22
    35
    48
    59
    132589
    heap size
    3

    7Swap the root, 5, into slot 3. The heap now has 3 items.

  8. a
    03
    11
    22
    35
    48
    59
    312589
    heap size
    3

    8Sift the 1 down by swapping it with its bigger child, 3. The children of index 1 are slots 3 and 4, which are outside the heap, so it stops.

  9. a
    02
    11
    23
    35
    48
    59
    213589
    heap size
    2

    9Swap the root, 3, into slot 2. The heap now has 2 items.

  10. a
    02
    11
    23
    35
    48
    59
    213589
    heap size
    2

    10The only child of the 2 is 1, which is smaller, so the 2 stays where it is.

  11. a
    01
    12
    23
    35
    48
    59
    123589
    heap size
    1

    11Swap the root, 2, into slot 1. One item is left, and it is already in place, so the array is sorted.

  12. a
    01
    12
    23
    35
    48
    59
    root swaps
    5
    sift swaps
    4

    12The sort used 5 root swaps and 4 sift swaps. Each sift followed a single path down the tree, which is never longer than log₂ n levels.

1 / 12

Code

function heapSort(a) {
  const n = a.length;
  // phase 1: build a max-heap, from the last parent up to the root
  for (let i = Math.floor(n / 2) - 1; i >= 0; i--) siftDown(a, i, n);
  // phase 2: move the max to the end, shrink the heap, repair it
  for (let end = n - 1; end > 0; end--) {
    [a[0], a[end]] = [a[end], a[0]];
    siftDown(a, 0, end); // the heap is now a[0..end-1]
  }
  return a;
}
 
function siftDown(a, i, size) {
  while (true) {
    let big = i;
    const left = 2 * i + 1, right = 2 * i + 2;
    if (left < size && a[left] > a[big]) big = left;
    if (right < size && a[right] > a[big]) big = right;
    if (big === i) return; // bigger than both children: done
    [a[i], a[big]] = [a[big], a[i]];
    i = big;
  }
}
 
heapSort([3, 8, 5, 1, 9, 2]); // [1, 2, 3, 5, 8, 9]
def heap_sort(a):
    n = len(a)
    # phase 1: build a max-heap, from the last parent up to the root
    for i in range(n // 2 - 1, -1, -1):
        sift_down(a, i, n)
    # phase 2: move the max to the end, shrink the heap, repair it
    for end in range(n - 1, 0, -1):
        a[0], a[end] = a[end], a[0]
        sift_down(a, 0, end)  # the heap is now a[0..end-1]
    return a
 
def sift_down(a, i, size):
    while True:
        big = i
        left, right = 2 * i + 1, 2 * i + 2
        if left < size and a[left] > a[big]:
            big = left
        if right < size and a[right] > a[big]:
            big = right
        if big == i:  # bigger than both children: done
            return
        a[i], a[big] = a[big], a[i]
        i = big
 
heap_sort([3, 8, 5, 1, 9, 2])  # [1, 2, 3, 5, 8, 9]

Time and space

Phase 2 performs n − 1 sift downs, and each one moves down at most log₂ n levels, so the sort is O(n log n) on every input. Unlike quicksort, there is no input that makes it slower.

Phase 1 is only O(n), even though it also performs n/2 sift downs. Half of the items are leaves and never move. A quarter of the items sit one level above the leaves and move at most one step, an eighth move at most two steps, and only the root can travel the full height. These counts add up to fewer than n swaps in total.

All of the work consists of swaps inside the array, so the extra space is O(1).

TimeO(n log n)
SpaceO(1)

O(n) to build the heap, then n − 1 sift downs of at most log n levels each. The cost is the same on every input. The sort is not stable.

Variants and alternatives

Building the heap by inserting one item at a time

Instead of sifting down from the last parent, you can start with a heap of one item and insert the remaining items one by one, sifting each new item up. This also produces a valid heap, but it takes O(n log n) because the items near the bottom, which are the majority, may each travel the full height upward. The sort as a whole is still O(n log n), but the bottom-up build above is the standard choice because it is faster and reuses the sift down that phase 2 needs anyway.

Sorting in descending order

To sort in descending order, use a min-heap, in which every parent is at most as large as its children, and make the same two phases. The smallest item is then moved to the end of the array each round, which leaves the array in descending order. In code, only the two comparisons in the sift down change direction.

Heap sort compared with quicksort and merge sort

Quicksort is O(n²) in the worst case but is usually the fastest of the three, because it reads memory in order and so works well with the CPU cache. Heap sort jumps between indexes that are far apart, such as 1, 3 and 7, which makes it slower in practice even though its operation count is the same order. Merge sort is O(n log n) in every case and is stable, but it needs O(n) extra memory for arrays. Heap sort is the only one of the three that has the O(n log n) guarantee and O(1) extra space at the same time.

When heap sort is not the right tool

Heap sort is not stable: swapping the root with the last item can move an item past other items that are equal to it, so the original order of equal keys is lost. If you need to keep it, for example when sorting records by one field after sorting by another, use merge sort. Heap sort also needs random access by index, so it does not suit linked lists, and when you only need the k largest items, you should not sort at all. Keep a min-heap of size k and push each item through it, which costs O(n log k).

Pitfalls

In the interview

Interviewers rarely ask you to write heap sort from scratch. When they do, the point is usually to check that you can implement a heap with array indexes. More often, the problem statement points to a heap, and the sorting step is a side issue. The signals are phrases such as "the k largest", "the k-th smallest", "the next largest item repeatedly" or "merge k sorted lists", and a requirement for O(n log n) time in the worst case with constant extra space. For the first group, use a heap of size k and do not sort at all. For the last one, heap sort is the answer.

These are the follow-up questions to expect.

  • "Why is building the heap O(n) and not O(n log n)?" Most items are near the bottom of the tree and can move only a few levels down. Half of the items are leaves and never move, a quarter move at most one level, and so on, so the total number of swaps is below n. The O(n log n) bound for phase 1 is correct but not tight.
  • "Is heap sort stable?" No. Swapping the root with the last item of the heap moves it over every item in between, including items equal to it, so equal keys can end up in a different order. To get a stable O(n log n) sort, use merge sort, and accept the extra memory.
  • "Why is quicksort usually faster if heap sort has a better worst case?" Quicksort scans memory in order, which suits the CPU cache, and it does fewer comparisons on average. Heap sort jumps between distant indexes and does two comparisons per level of each sift down. Real libraries combine them: introsort starts with quicksort and switches to heap sort if the recursion gets too deep, which keeps the worst case at O(n log n).
  • "When would you choose heap sort?" When memory is tight, so merge sort is out, and a bad worst case is not acceptable, so plain quicksort is out. That is a narrow case, and saying so is a good answer.
  • "How would you find the 10 largest of a million numbers?" Keep a min-heap of size 10. For each number, if it is larger than the heap's root, replace the root with it and sift down. This takes O(n log 10) time and O(10) memory, while sorting everything would take O(n log n).
  • "Can you do it without recursion?" Yes. The sift down in the code above is a loop, so the whole sort is iterative and uses no call stack.
Quick check

In a heap stored as an array, where are the children of index 2?

Why does phase 1 start at index n/2 − 1 instead of at the last index?

You must sort 10 million numbers with a guaranteed O(n log n) running time and almost no extra memory. Which sort fits?

Which statement about heap sort is true?

What to practise next

Merge sort, quicksort and heap sort all work by comparing items, and no comparison sort can beat O(n log n). Counting and Radix Sort avoids comparisons entirely, and that lesson ends with a table that compares every sort in this module.