AlgoViz

Heap sort

medium 18 min

Heap sort turns the array into a max-heap in O(n), then repeatedly swaps the root (the maximum) to the end and sifts the new root down in O(log n).

Where it shows up

The same pattern appears across everyday software.

  • C++ std::sort (introsort)

    GCC's libstdc++ and LLVM's libc++ run quick sort but switch to heap sort when the recursion depth passes about 2 log2 n, so a hostile input can never force O(n²).

  • .NET Array.Sort

    Since .NET Framework 4.5, Array.Sort uses introspective sort: quick sort, insertion sort for small partitions, and heap sort as the depth-limit fallback.

  • Linux kernel sort()

    The kernel's generic lib/sort.c is a heap sort: no recursion, no extra memory and a hard O(n log n) bound, which matter more in the kernel than average speed.

  • Top-k queries and leaderboards

    Showing the 10 best scores out of millions needs only a partial heap sort or a size-10 heap, as in Python's heapq.nlargest.

  • Embedded and real-time systems

    Firmware that sorts sensor readings or task lists favours heap sort for its fixed memory use and predictable worst-case time.

  • Priority schedulers

    Operating system and network schedulers keep jobs in a heap; draining the heap in order is heap sort's extraction phase.