Algorithm · Sorting and selection · O(n log n), O(1) extra

Heap sort

Build a max-heap in place, then repeatedly swap the root to the end and sift down. O(n log n) worst case, O(1) extra space, not stable.

The full derivation, edge cases and exercises are in the lesson Heap sort. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Heap sort turns the array itself into a max-heap in O(n), so the largest element is at index 0. Swapping it with the last element of the heap fixes it in place; one sift-down restores the heap on the shorter prefix. n − 1 rounds sort the array.

It has merge sort’s guaranteed bound and quicksort’s in-place memory, but its jumps through the array are unfriendly to caches, so it is usually slower in practice. Introsort uses it as a fallback.

Steps

  1. Heapify: sift down every internal node from the last one to the root.
  2. Swap a[0] with the last heap element; the heap shrinks by one.
  3. Sift the new root down; repeat until one element is left.

Invariants

What holds at every step; the correctness argument rests on these.

  • a[0 … end) is a max-heap; a[end … n) holds the largest elements in sorted order.

Complexity

Heap sort complexity
CaseTimeExtra space
Build heapO(n)O(1)
All casesO(n log n)O(1)

When to use it

Use it when

  • You need an O(n log n) guarantee with no extra memory.

Avoid it when

  • Stability matters, or typical-case speed matters more than the worst case.

Step through it

The interactive lab for heap sort: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Lessons

Data structures it uses

Problems, patterns and exercises

References