AlgoFrames

Heap sort

Heap sort builds a max-heap, then repeatedly moves the maximum to the end and shrinks the heap. It sorts in place in O(n log n).

Before you start: Building a heap in O(n).

The idea

Selection sort scans the whole array to find each maximum. A max-heap hands over its maximum, 9, in one look.

After the max leaves, the heap repairs itself in O(log n). So n rounds cost O(n log n) instead of O(n²).

Intuition

The array has two parts. The front is a max-heap, and the back holds the largest values in final order.

The max 9 sits at index 0. The heap's last cell, index 6, is where 9 belongs, so one swap puts it there.

After the swap, 7 sits at the root of a smaller heap. One sift down repairs it, and the next round starts.

The sift only looks at cells 0 to 5. Cell 6 now belongs to the sorted part and must not move again.

Complexity

Build-heap costs O(n), and each of the n - 1 rounds costs one O(log n) sift. Heap sort is O(n log n) in every case.

Even a sorted input needs every sift, so there is no fast best case. For 128 values that is about 1,800 comparisons against 8,128.

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

Pitfalls

The sift must stop at the end of the heap. Sifting with size n pulled the sorted 9 back up to index 2.

Heap sort is not stable. Sorting 5a, 5b, 3 gives 3, 5b, 5a, so the equal 5s change order.

The swap from the root to the end jumps over equal values. Use merge sort when equal keys must keep their order.

Variations

Stop after k rounds to get the k largest values in O(n + k log n). Here 2 rounds give 8 and 9.

Introsort runs quicksort and switches a part to heap sort when the recursion gets too deep. C++ std::sort works this way.

Code

Pseudocode

heap_sort(a)
  n ← length of a
  build_heap(a)
  for end from n - 1 down to 1
    swap a[0] and a[end]
    sift_down(a, 0, end)

sift_down(a, i, size)
  loop
    c ← the larger child of i below size
    if c does not exist or a[i] ≥ a[c]: stop
    swap a[i] and a[c]
    i ← c

Python

def heap_sort(a):
    n = len(a)
    for i in range(n // 2 - 1, -1, -1):
        sift_down(a, i, n)
    for end in range(n - 1, 0, -1):
        a[0], a[end] = a[end], a[0]
        sift_down(a, 0, end)

def sift_down(a, i, size):
    while True:
        c = 2 * i + 1
        if c >= size: return
        if c + 1 < size and a[c + 1] > a[c]: c += 1
        if a[i] >= a[c]: return
        a[i], a[c] = a[c], a[i]
        i = c

JavaScript

function heapSort(a) {
  const n = a.length;
  for (let i = (n >> 1) - 1; i >= 0; i--) siftDown(a, i, n);
  for (let end = n - 1; end > 0; end--) {
    [a[0], a[end]] = [a[end], a[0]];
    siftDown(a, 0, end);
  }
}

function siftDown(a, i, size) {
  while (true) {
    let c = 2 * i + 1;
    if (c >= size) return;
    if (c + 1 < size && a[c + 1] > a[c]) c++;
    if (a[i] >= a[c]) return;
    [a[i], a[c]] = [a[c], a[i]];
    i = c;
  }
}

Java

static void heapSort(int[] a) {
    int n = a.length;
    for (int i = n / 2 - 1; i >= 0; i--) siftDown(a, i, n);
    for (int end = n - 1; end > 0; end--) {
        int tmp = a[0]; a[0] = a[end]; a[end] = tmp;
        siftDown(a, 0, end);
    }
}

static void siftDown(int[] a, int i, int size) {
    while (true) {
        int c = 2 * i + 1;
        if (c >= size) return;
        if (c + 1 < size && a[c + 1] > a[c]) c++;
        if (a[i] >= a[c]) return;
        int tmp = a[i]; a[i] = a[c]; a[c] = tmp;
        i = c;
    }
}

Cost at a glance

BestO(n log n)
AverageO(n log n)
WorstO(n log n)
SpaceO(1)
Stableno
In-placeyes
Adaptiveno

Practice problems (7)

Stability Warm-up

Heap sort sorts the cards 5a, 5b, 3 by number only. The letters just tell the two 5s apart. Which result does heap sort give, and what does it show?

Match each part of heap sort to its cost Warm-up

Heap sort on n values has a few parts. Match each part to its worst-case cost.

State after two extractions Standard

Heap sort runs on [6, 3, 8, 1, 9, 2, 7]. Build-heap gives [9, 6, 8, 1, 3, 2, 7].

Predict where the first max goes, then arrange the array after two rounds of swap and sift.

Implement heap sort Standard

Sort values in ascending order with heap sort and return the array. Build a max-heap in place, then repeatedly swap the root with the last cell of the heap and sift the new root down.

Do not call a library sort.

The k largest values Standard

Return the k largest values of values, largest first. Build a max-heap, then run only k rounds of heap sort: each round takes the root.

Duplicates count separately, so [5, 5, 1] with k = 2 gives [5, 5].

Spot the bug: the heap that never shrinks Standard

This heap sort returns a wrong order for most inputs with three or more values. Click the line with the bug, then fix it.

Sort nearly sorted data with a small heap Challenge

In values, every value is at most k cells away from its place in sorted order. Return the values sorted in ascending order.

Keep a min-heap of only k + 1 values: the smallest of the next k + 1 values must be the next output. Aim for O(n log k) time and O(k) extra memory.

Related topics

Next on the path: Priority queues in practice: top-k, k-way merge, scheduling