M21 · Heaps and Priority Queues

Heap Sort

Heap sort turns the array into a max-heap, then repeatedly swaps the root (the largest remaining value) with the last slot of the heap and shrinks the heap by one. The sorted part grows from the right. It needs no extra array and never degrades to quadratic time, which is why library sorts use it as their safety net.

~35 minIntermediateC# · Python · Java · C++
Curriculum: M21 Heaps and Priority Queues · 2 of 2 lessons available

You will be able to

  • Explain why ascending heap sort uses a max-heap and where the sorted part of the array lives.
  • Trace the build phase (bottom-up heapify) and the extraction phase, including each sift down.
  • Derive O(n log n) time in every case and O(1) extra space, and compare with merge sort and quicksort.
  • Show with an example why heap sort is not stable.
  • Explain why introsort falls back to heap sort and why heap sort is rarely the fastest choice on its own.

Helpful before this lesson

  • M13 Sorting — Stability, in-place sorting, the classic algorithms and what built-in sorts actually do.
  • M21 Heaps and Priority Queues — The array-backed heap, sift operations, O(n) heapify and heap sort.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

This lesson builds on Heaps and priority queues: the array-as-tree layout, sift down and bottom-up heapify are used here without re-deriving them.

Mental model

Pop from a priority queue n times and the values come out sorted. Heap sort does exactly that, but without a second array: the heap and the output share one array.

  • The heap occupies the front, items[0..heapSize).
  • The sorted output occupies the back, items[heapSize..n), and grows leftwards.

Each step removes the heap's root and puts it into the slot the shrinking heap just gave up. For ascending order the root must be the largest remaining value, so heap sort uses a max-heap: every parent is greater than or equal to its children.

The two phases

build:   for i = n/2 − 1 down to 0:  siftDown(i, n)          (max-heap over the whole array)
extract: for end = n − 1 down to 1:
             swap items[0], items[end]                        (the maximum goes to its final slot)
             siftDown(0, end)                                 (restore the heap in items[0..end))

siftDown(i, size) compares the two children of i that lie inside the heap, takes the larger (the left one on ties), and swaps if that child is larger than items[i]; it repeats from the child and stops at a leaf or when the parent is not smaller. Elements at size and beyond are invisible to it, which is how the sorted tail stays untouched.

A small example

Sort 4 10 3 5 1.

Build. n = 5, so the parents are indices 1 and 0. Index 1 (10) is already larger than its children 5 and 1. Index 0 (4): the larger child is 10, swap → 10 4 3 5 1; continue at index 1: the larger child is 5, swap → 10 5 3 4 1. That is a max-heap.

Extract.

Step Swap root with Array after the swap After sift down
end = 4 1 1 5 3 4 │ 10 5 4 3 1 │ 10
end = 3 1 1 4 3 │ 5 10 4 1 3 │ 5 10
end = 2 3 3 1 │ 4 5 10 3 1 │ 4 5 10
end = 1 1 1 │ 3 4 5 10 done

The bar separates the heap from the sorted tail. In the lab the tree above the array shows only the heap part; slots of the tail turn green and leave the tree.

Cost

  • Build: O(n), by the same height argument as heapify in the previous lesson.
  • Extract: n − 1 sift downs on heaps of size n − 1, n − 2, …, 1. Each costs at most ⌊log₂ size⌋ levels with two comparisons per level, so the phase is O(n log n), and for most inputs most sifts go nearly to the bottom, so it is also Ω(n log n).
  • Total: Θ(n log n) comparisons in the best, average and worst case, about 2n log₂ n in the worst case for this standard version.
  • Space: O(1) extra. The sift down is a loop, not recursion, and no buffer is needed.

The Already sorted preset shows there is no shortcut: building the max-heap first moves the large values to the front, which scrambles the sorted input before extraction sorts it again.

Not stable

Run the Not stable preset: 5a 1 5b 2 5c. Building the heap leaves 5a 5c 5b 2 1, and the extractions move the root to the end each time. The result is 1 2 5b 5c 5a: the three equal 5s come out in a different order than they went in. The long root-to-end swap jumps elements over equal ones, and nothing ever restores their original order.

How it compares

Heap sort Merge sort Quicksort (tuned)
Worst-case time Θ(n log n) Θ(n log n) Θ(n²), avoided in practice by random or median pivots and introsort
Extra space O(1) O(n) O(log n) stack
Stable no yes no
Adaptive to sorted input no not this version (Timsort is) depends on pivot
Memory access jumps between i and 2i + 1: poor cache locality on large arrays sequential sequential

Heap sort's guarantees are excellent and its constant factors are not. Each sift down jumps from index i to about 2i, so on large arrays nearly every step touches a different cache line, and it makes more comparisons than quicksort on average. That is why it is rarely the default sort, and exactly why it is the perfect fallback.

Where it runs

  • Introsort (C++ std::sort in libstdc++ and libc++, C# Array.Sort): quicksort normally, but when the recursion depth passes a limit around 2 log₂ n, the current range is finished with heap sort. That caps the worst case at O(n log n) without giving up quicksort's average speed.
  • C++ std::partial_sort (the k smallest elements, sorted) is typically a heap of size k: O(n log k). std::make_heap followed by std::sort_heap is a complete heap sort you can call directly.
  • Top-k problems in any language use the same idea with a priority queue (see the previous lesson's third practice question).

Variants worth knowing

  • Bottom-up heap sort (Floyd's idea): during extraction, sift the hole all the way down by choosing the larger child without comparing against the moved element, then sift the element up from the bottom. Since the moved element usually belongs near the bottom anyway, this saves about half of the comparisons.
  • d-ary heaps (more than two children per node) make the tree shallower; .NET's PriorityQueue uses four children per node.

The teaching implementation

HeapSort.Sort / heap_sort takes a comparison (or a key in Python) and sorts ascending with the rules above: the larger child, the left one on ties, and a swap only when the child is strictly larger. Because heap sort is unstable, the shared fixture records the exact order this implementation leaves equal keys in (4a 4b 4c 4d becomes 4b 4c 4d 4a), and all four languages must reproduce it; each is also compared with its built-in sort on 500 random inputs.

Common mistakes

  • Using a min-heap for ascending order in place. The minimum would have to go to the front, which is where the heap lives. Use a max-heap (or sort descending with a min-heap).
  • Sifting down over the whole array instead of items[0..end): the sorted tail gets pulled back into the heap.
  • Building the heap top-down with n sift ups: correct, but O(n log n) for the build instead of O(n).
  • Expecting stability because the output "looks" ordered on small examples.

Worked practice

1. After the build phase on 2 8 5 3 9 1, what is the array?

Answer

9 8 5 3 2 1. Index 2 (5) has one child, 1, and stays. Index 1 (8): children 3 and 9; 9 is larger and larger than 8, swap → 2 9 5 3 8 1. Index 0 (2): children 9 and 5; swap with 9 → 9 2 5 3 8 1; continue at index 1: children 3 and 8; swap with 8 → 9 8 5 3 2 1.

2. How many root-to-end swaps does heap sort make on n elements?

Answer

Exactly n − 1, one per extraction (end = n − 1 down to 1). The last element left in the heap is the smallest and is already at index 0.

3. Why can heap sort guarantee O(n log n) when quicksort cannot?

Answer

Its work does not depend on lucky choices. The heap is always a complete tree of height ⌊log₂ n⌋, so every sift down is bounded by that height whatever the values are. Quicksort's recursion depth depends on where the pivots land, which can be anywhere.

Summary

  • Build a max-heap in O(n); then n − 1 times, swap the root to the end of the heap and sift down.
  • Θ(n log n) comparisons in every case, O(1) extra space, not stable.
  • Poor cache locality makes it slower than quicksort on average, so libraries use it as introsort's worst-case fallback.

Full implementation

Heap sort in four languages, each checked against one shared fixture that pins down the exact (unstable) order of equal keys, and 500 random inputs whose keys are compared with the language's built-in sort.

namespace Bekadan.Dsa.Examples.Sorting;
 
/// <summary>
/// Heap sort, ascending: build a max-heap in place, then move the maximum to
/// the end n - 1 times. O(n log n) comparisons in every case, O(1) extra
/// space, not stable.
/// </summary>
public static class HeapSort
{
    public static void Sort<T>(T[] items, Comparison<T> compare)
    {
        int n = items.Length;
        for (int i = n / 2 - 1; i >= 0; i--) // indices n/2 .. n-1 are leaves
            SiftDown(items, i, n, compare);
        for (int end = n - 1; end > 0; end--)
        {
            (items[0], items[end]) = (items[end], items[0]); // the maximum goes to its final slot
            SiftDown(items, 0, end, compare);                // the heap is now items[0..end)
        }
    }
 
    /// <summary>Moves items[i] down until it is >= both children inside items[0..size).</summary>
    private static void SiftDown<T>(T[] items, int i, int size, Comparison<T> compare)
    {
        while (true)
        {
            int child = 2 * i + 1;
            if (child >= size)
                return; // a leaf
            if (child + 1 < size && compare(items[child + 1], items[child]) > 0)
                child++; // the larger child (the left one on ties)
            if (compare(items[child], items[i]) <= 0)
                return; // the parent is not smaller than its children
            (items[i], items[child]) = (items[child], items[i]);
            i = child;
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/HeapSort.cs

"""Heap sort, ascending.
 
Build a max-heap in place, then move the maximum to the end n - 1 times.
O(n log n) comparisons in every case, O(1) extra space, not stable.
"""
 
from collections.abc import Callable
from typing import Any
 
 
def _identity(item: Any) -> Any:
    return item
 
 
def heap_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
    n = len(items)
    for i in range(n // 2 - 1, -1, -1):  # indices n // 2 .. n - 1 are leaves
        _sift_down(items, i, n, key)
    for end in range(n - 1, 0, -1):
        items[0], items[end] = items[end], items[0]  # the maximum goes to its final slot
        _sift_down(items, 0, end, key)  # the heap is now items[0:end]
 
 
def _sift_down(items: list[Any], i: int, size: int, key: Callable[[Any], Any]) -> None:
    """Moves items[i] down until it is >= both children inside items[0:size]."""
    while True:
        child = 2 * i + 1
        if child >= size:
            return  # a leaf
        if child + 1 < size and key(items[child + 1]) > key(items[child]):
            child += 1  # the larger child (the left one on ties)
        if key(items[child]) <= key(items[i]):
            return  # the parent is not smaller than its children
        items[i], items[child] = items[child], items[i]
        i = child

Tested on CPython 3.14.0 · examples/python/dsa_examples/heap_sort.py

package dev.bekadan.dsa.sorting;
 
import java.util.Comparator;
 
/**
 * Heap sort, ascending: build a max-heap in place, then move the maximum to
 * the end n - 1 times. O(n log n) comparisons in every case, O(1) extra
 * space, not stable.
 */
public final class HeapSort {
    private HeapSort() {
    }
 
    public static <T> void sort(T[] items, Comparator<? super T> comparator) {
        int n = items.length;
        for (int i = n / 2 - 1; i >= 0; i--) { // indices n/2 .. n-1 are leaves
            siftDown(items, i, n, comparator);
        }
        for (int end = n - 1; end > 0; end--) {
            swap(items, 0, end);                   // the maximum goes to its final slot
            siftDown(items, 0, end, comparator);   // the heap is now items[0..end)
        }
    }
 
    /** Moves items[i] down until it is &gt;= both children inside items[0..size). */
    private static <T> void siftDown(T[] items, int i, int size, Comparator<? super T> comparator) {
        while (true) {
            int child = 2 * i + 1;
            if (child >= size) {
                return; // a leaf
            }
            if (child + 1 < size && comparator.compare(items[child + 1], items[child]) > 0) {
                child++; // the larger child (the left one on ties)
            }
            if (comparator.compare(items[child], items[i]) <= 0) {
                return; // the parent is not smaller than its children
            }
            swap(items, i, child);
            i = child;
        }
    }
 
    private static <T> void swap(T[] items, int a, int b) {
        T tmp = items[a];
        items[a] = items[b];
        items[b] = tmp;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/HeapSort.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
#include <utility>
 
namespace bekadan::dsa {
 
// Heap sort, ascending: build a max-heap in place, then move the maximum to
// the end n - 1 times. O(n log n) comparisons in every case, O(1) extra
// space, not stable. (std::make_heap + std::sort_heap do the same.)
 
namespace detail {
 
// Moves items[i] down until it is >= both children inside items[0..size).
template <typename T, typename Less>
void sift_down_max(std::span<T> items, std::size_t i, std::size_t size, Less& less) {
    while (true) {
        std::size_t child = 2 * i + 1;
        if (child >= size)
            return;  // a leaf
        if (child + 1 < size && less(items[child], items[child + 1]))
            ++child;  // the larger child (the left one on ties)
        if (!less(items[i], items[child]))
            return;  // the parent is not smaller than its children
        std::swap(items[i], items[child]);
        i = child;
    }
}
 
}  // namespace detail
 
template <typename T, typename Less = std::less<>>
void heap_sort(std::span<T> items, Less less = {}) {
    const std::size_t n = items.size();
    for (std::size_t i = n / 2; i-- > 0;)  // i = n/2 - 1 down to 0; indices n/2 .. n-1 are leaves
        detail::sift_down_max(items, i, n, less);
    for (std::size_t end = n; end-- > 1;) {  // end = n - 1 down to 1
        std::swap(items[0], items[end]);              // the maximum goes to its final slot
        detail::sift_down_max(items, 0, end, less);   // the heap is now items[0..end)
    }
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/heap_sort.hpp

References