Heap sort

Take the maximum and leave it at the end Β· Part of Search and sort

Key idea

Practice

6 questions Β· about 3 min

Explained step by step

Heap sort

Heap sort uses a heap to sort. First it builds a max-heap from the array, in O(n): the largest ends up at index 0. Then it swaps the root with the heap's last element, so the largest lands at the end, in its final place. The heap shrinks by 1 and the new root is sunk so it's a heap again. This repeats n βˆ’ 1 times and the array ends up sorted from smallest to largest.

To trace it by hand with [3, 1, 2]: once the max-heap is built, it's [3, 1, 2], with 3 at the root. Round 1: 3 is swapped with the last, [2, 1, 3]; the heap is now [2, 1] and 2 already fits. Round 2: 2 is swapped with 1, [1, 2, 3]; the heap has 1 element and it's done. Result: [1, 2, 3].

Building the heap costs O(n), and each of the n βˆ’ 1 rounds costs O(log n) for the sinking: O(n log n) in total, always, whatever the data's order. It isn't adaptive. It works in the same array, with a few variables: O(1) memory, in place. And it isn't stable: swapping the root with the last can cross equal elements.

The simplest version of heap sort builds a min-heap and removes the root n times, writing each into a new array: they come out from smallest to largest. It works, but needs an extra array of n. The in-place version uses a max-heap and leaves each maximum at the end of the same array, in the spot the heap just freed. That way no extra memory is needed.

Heap sort guarantees O(n log n) and is in place, but in practice it's usually slower than quick sort. The main reason is the cache: when sinking a node, it jumps from index i to 2i + 1, very distant positions in large arrays, and almost every jump is a cache miss. Quick sort, on the other hand, walks contiguous pieces of the array. Heap sort also does more comparisons and swaps in total.

Stable sort

Heap sort isn't stable: swapping the root with the heap's last element can move an element past an equal one. For example, with 2 elements of value 5, the one that was earlier can end up later. That's why, if stability is needed, merge sort is used.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Take the maximum and leave it at the end