Tiem Cong Nghe

Showing suggestions.

Opening the store's index…
↑↓ to move↵ to openesc to close
Tiem Cong Nghe search

Free explainer · Video · Code · Quiz

Heap Sort

Treat the array as a binary tree, build a max-heap with siftDown, then keep swapping the biggest value to the end and repairing the shrinking heap. In place, O(n log n) in the worst case, O(1) extra space.

Difficulty
Medium
Time
O(n log n)
Space
O(1)

Try it yourself

Step through it at your own pace — this is Heap Sort Animation, running right on the page.

Get this code

LiveHeap Sort Animation

Loading the preview…

How it works

The idea, a worked example, and the traps to avoid.

The idea

Picture a tournament bracket where the winner of every match is the bigger of its two players. Whoever stands at the top is the biggest of all. Take that champion out, put it at the very end of the line, and replay only the matches along one path to crown a new champion. Repeat, and the line fills up from the back, biggest first. That's heap sort.

The bracket is a max-heap: a tree where every parent is at least as big as its children. It's not sorted (a parent's two children can be in either order), but it always keeps the maximum at the root, and fixing it after the root changes costs only one walk down the tree. That cheap "give me the biggest" operation is the whole trick.

The array is the tree

You don't need nodes or pointers. A complete binary tree (every level full except maybe the last, filled left to right) fits into an array with plain arithmetic:

  • the children of index i are at 2i + 1 and 2i + 2;
  • the parent of index i is at floor((i - 1) / 2).

For [7, 2, 9, 4, 3, 8, 1] that gives this tree:

        7            index 0
      /   \
     2     9         index 1, 2
    / \   / \
   4   3 8   1       index 3, 4, 5, 6

The heap lives in the front of the array, and the sorted part grows from the back. The two never need separate memory.

Walkthrough

Phase 1: build the max-heap. siftDown(values, root, size) takes a value and sinks it: compare it with its bigger child, and if the child is bigger, swap and continue from there. We call it on every parent, from the last one back to index 0. For 7 values the last parent is index floor(7 / 2) - 1 = 2.

Root What happens Array
2 children 8 and 1: the 9 is big enough, stays [7, 2, 9, 4, 3, 8, 1]
1 children 4 and 3: the 2 swaps with the bigger one, 4 [7, 4, 9, 2, 3, 8, 1]
0 children 4 and 9: 7 swaps with 9, then at index 2 meets 8 and 1 and swaps with 8 [9, 4, 8, 2, 3, 7, 1]

Going from the last parent back to the root matters: when we reach a value, both subtrees below it are already heaps, so one sink is enough to fix it.

Phase 2: sort. The root is the biggest value. Swap it with the last value of the heap, and that position is final. The heap is one shorter now, and its new root is probably too small, so sift it down within the smaller heap.

end After the swap After siftDown (heap is the part left of end)
6 [1, 4, 8, 2, 3, 7, 9] [8, 4, 7, 2, 3, 1, 9]
5 [1, 4, 7, 2, 3, 8, 9] [7, 4, 1, 2, 3, 8, 9]
4 [3, 4, 1, 2, 7, 8, 9] [4, 3, 1, 2, 7, 8, 9]
3 [2, 3, 1, 4, 7, 8, 9] [3, 2, 1, 4, 7, 8, 9]
2 [1, 2, 3, 4, 7, 8, 9] [2, 1, 3, 4, 7, 8, 9]
1 [1, 2, 3, 4, 7, 8, 9] nothing left to sift

The loop stops at end = 1: a heap of one value is already in place.

The choices in this code

One siftDown for both phases. Phase 1 calls it with size equal to the array length; phase 2 calls it with size = end, so the sorted tail is simply out of reach. No copying, no slicing.

Ties are fixed. Between two equal children biggerChild picks the left one, and a parent that equals its bigger child stays put (>=, not >). That keeps every run deterministic: the same swaps, in the same order, in every language.

Bottom-up instead of inserting one by one. You could build the heap by pushing values in one at a time (sift up), but that costs O(n log n). Sinking from the last parent is O(n), as explained below.

Why it's correct

After phase 1 every parent is ≥ its children, so the root is the maximum. In phase 2 each round moves the maximum of the remaining heap to its final index. Then siftDown restores the heap property: the new root's two subtrees are still heaps (we only removed a leaf and replaced the root), and sinking along the bigger child's path puts every value above its children again. After n - 1 rounds, the back of the array holds the values in ascending order and one value is left in front.

Complexity

  • Phase 2: O(n log n). n - 1 sifts, and a sift walks down at most the height of the tree, about log₂ n levels.
  • Phase 1: O(n), not O(n log n). Half of all nodes are leaves and never move. A quarter sink at most one level, an eighth at most two, and so on. The total work is a series that adds up to less than 2n. Most nodes are near the bottom, where sinking is cheap.
  • Time: O(n log n) in the best, average and worst case. No input makes it quadratic, which is its edge over quick sort. It doesn't speed up on nearly sorted data either.
  • Space: O(1). Everything happens inside the array, and the loops need no recursion.
  • Not stable. The swap of the root with the last value jumps over everything in between. Sorting [2, 2, 1] with the two 2s labelled a and b gives [1, 2b, 2a]. Use merge sort when equal items must keep their order.

In practice heap sort is usually slower than quick sort on arrays, because it hops around memory (index i to 2i + 1), which caches dislike. You pick it for its guarantees.

Common bugs

  • Wrong child indices. With 0-based arrays it's 2i + 1 and 2i + 2. The 2i and 2i + 1 formulas belong to 1-based heaps.
  • Starting the build at size - 1, or at size / 2. The first parent is floor(size / 2) - 1. Leaves have nothing to sink.
  • Reading a missing right child. When 2i + 2 >= size, there is only a left child. Compare against size, not values.length, or you drag sorted values back into the heap.
  • Forgetting the heap shrank. After the swap, siftDown must get end, not the old size.
  • Overflow in 2 * parent + 1 in Java or C++ for arrays near 2³⁰ values. Rarely a concern, but it's why some code uses long.

When to use it (and when not)

Use it when you need a guaranteed O(n log n) with no extra memory: embedded code, or as the fallback that stops introsort from going quadratic (C++'s std::sort does exactly this). Look elsewhere for stability (merge sort) or the best speed on ordinary arrays (quick sort or the built-in sort).

The data structure behind it: the binary heap

The same array layout is a binary heap, the usual way to build a priority queue:

  • peek the biggest: read index 0, O(1);
  • pop the biggest: swap the root with the last value, shrink by one, siftDown: O(log n). That's one round of phase 2;
  • push a value: add it at the end and sift it up while it's bigger than its parent: O(log n).

Dijkstra's algorithm, task schedulers and "top k" queries all run on this. Heap sort is just "build a heap, then pop everything".

Interview variations

  1. K largest elements. Keep a min-heap of size k: push each value, pop the smallest when the heap grows past k. O(n log k) time, O(k) space, and it works on a stream.
  2. Merge k sorted lists. Keep the current head of each list in a min-heap, pop the smallest, push the next value from the same list. O(N log k) for N values in total.
  3. Median of a stream. Two heaps: a max-heap for the lower half, a min-heap for the upper half. The median sits at one of the roots.
  4. Is this array a valid max-heap? For every index i > 0, check values[floor((i - 1) / 2)] >= values[i]. One pass.

Code

The same algorithm, step for step, in 4 languages.

JavaScript
// Heap sort, in place: build a max-heap, then keep moving the biggest value to the end.
// The array doubles as a complete binary tree: the children of index i sit at 2i + 1 and 2i + 2.

/**
 * Sorts `values` in ascending order, in place.
 * Not stable: equal values may end up in a different order than they started.
 *
 * @param {number[]} values the array to sort
 * @returns {void}
 */
export function heapSort(values) {
  const size = values.length;

  // Phase 1: turn the array into a max-heap, from the last parent back to the root.
  for (let root = Math.floor(size / 2) - 1; root >= 0; root--) {
    siftDown(values, root, size);
  }

  // Phase 2: the root is the biggest value left. Park it at the end, then repair the heap.
  for (let end = size - 1; end > 0; end--) {
    swap(values, 0, end);
    siftDown(values, 0, end); // the heap is now values[0..end - 1]
  }
}

/**
 * Sinks values[root] until both of its children are no bigger than it.
 * Only values[0..size - 1] count as the heap; everything after is already sorted.
 * Assumes the two subtrees under `root` are already max-heaps.
 *
 * @param {number[]} values
 * @param {number} root index of the value to sink
 * @param {number} size how many values at the front still belong to the heap
 */
export function siftDown(values, root, size) {
  let parent = root;

  while (true) {
    const left = 2 * parent + 1;
    if (left >= size) return; // no children: the value is a leaf, it stays

    const child = biggerChild(values, left, size);
    if (values[parent] >= values[child]) return; // the parent is big enough: heap restored

    swap(values, parent, child); // the bigger child moves up, the parent sinks one level
    parent = child;
  }
}

/**
 * Of the children `left` and `left + 1`, returns the index of the bigger one.
 * A tie goes to the left child, and a missing right child is never read.
 *
 * @param {number[]} values
 * @param {number} left index of the left child
 * @param {number} size
 * @returns {number}
 */
function biggerChild(values, left, size) {
  const right = left + 1;
  if (right >= size) return left; // only one child
  return values[right] > values[left] ? right : left;
}

/**
 * @param {number[]} values
 * @param {number} a
 * @param {number} b
 */
function swap(values, a, b) {
  [values[a], values[b]] = [values[b], values[a]];
}

Test yourself

10 quick questions to check it stuck.

Q1 · In the array [7, 2, 9, 4, 3, 8, 1] viewed as a tree, which values are the children of the 9 at index 2?

Take the quiz

Take it further

  • Animation

    Heap Sort Animation

    The array and the binary tree it stands for, side by side: every sink moves both at once, the heap shrinks and the sorted tail locks in

    Free