Lesson 38 · Core algorithms

Heap Sort

Heap sort turns the array into a max-heap, then repeatedly swaps the largest value to the end and repairs the heap over what is left. It sorts in place in O(n log n) time on every input, but it is not stable.

Heap Sort concept diagramA visual explanation of the layout and operations shown in this lesson.the array is a complete binary tree: children of i sit at 2i+1 and 2i+29i=07i=18i=23i=35i=42i=5max-heap: every parent is ≥ both children, so the root is the maximumswap the root to the end, shrink the heap, sift down — repeat
1

How Heap Sort Works

  1. Build a max-heap: sift down every parent, from index n // 2 - 1 back to 0
  2. Swap the root (the maximum) with the last value of the heap
  3. Shrink the heap by one; the swapped value is now in its final place
  4. Sift the new root down to repair the heap
  5. Repeat until one value is left

Heap sort needs no extra nodes or pointers. A plain array already is a complete binary tree if you read the indexes arithmetically: the children of index i are at 2i + 1 and 2i + 2, and its parent is at (i − 1) // 2.

A max-heap adds one rule: every parent is at least as large as its children. That is much weaker than sorted (siblings can be in any order), but it guarantees the one thing the algorithm needs: the maximum is at index 0.

So the array does two jobs at once. The front is the heap; the back is the sorted output, growing leftward one value per extraction. Nothing else is allocated, which is where the O(1) space comes from.

  • Indexes from n // 2 to n - 1 are leaves and need no work
  • A heap is not sorted: only the root is guaranteed
2

Sift Down

  1. Compare the node with its children that are still inside the heap
  2. If the node is at least as large as the larger child, stop
  3. Otherwise swap it with the larger child
  4. Repeat from the child's position until the node fits or becomes a leaf

Sift down is the one operation heap sort is built from. It assumes both subtrees of a node are already valid heaps and only the node itself may be too small.

Swapping with the larger child is essential. If the node swapped with the smaller child instead, that child would become the parent of its larger sibling and break the heap rule; the next extraction would then put the wrong value at the end.

Each swap moves the value down one level, so a sift costs at most the tree height, O(log n). The opposite operation, sift up, is used when inserting into a heap or priority queue, but heap sort never needs it: it only removes from the root.

  • Only the part of the array still inside the heap is compared
  • Cost: O(log n) per sift
3

Heap Sort Time Complexity

Building the heap costs O(n) (shown below), and each of the n − 1 extractions costs one swap plus a sift down of O(log n). The total is O(n log n), and unlike quick sort it does not depend on the input order: sorted, reversed and random arrays all take O(n log n).

  • Time complexity: best, average and worst O(n log n)
  • Space complexity: O(1) extra, sorted in place

The best case is also O(n log n) for distinct values: even on sorted input, every extraction moves a small value to the root, which then sinks most of the way down. Only special inputs such as all-equal values finish faster.

Space is O(1) extra: the heap and the output share the input array, and the code uses loops rather than recursion.

  • Guaranteed O(n log n): no bad input exists
  • O(1) space is its edge over merge sort, which needs O(n)
Key reference

Terms, operations, and practical uses

Core mechanics

  • Sift downPushing a value toward the leaves by repeatedly swapping with its larger child until the heap property holds.
  • Build-heapSifting down every internal node from the last one upward — O(n), not O(n log n).
  • Extract phaseSwapping the root with the last element, shrinking the heap, and sifting the new root down.

Properties

  • Not stableSift-down moves values across long distances, so equal keys can be reordered.
  • O(n log n) worst caseO(n log n) on every input, the guarantee quick sort cannot offer.
  • In-placeThe heap occupies the same array as the sorted output, growing from opposite ends.

Where it is used

  • IntrosortC++ std::sort switches to heap sort when quicksort's recursion runs too deep, capping the worst case.
  • Real-time systemsChosen when a hard upper bound matters more than average speed.
  • Priority queueThe same structure without the extract loop — heapq in Python, PriorityQueue in Java.
Implementation

Code in Python, C++ and Java

def heap_sort(values):
    n = len(values)
    # build a max-heap: start at the last parent and work backwards
    for i in range(n // 2 - 1, -1, -1):
        sift_down(values, i, n)
    # repeatedly move the root to the end and shrink the heap
    for end in range(n - 1, 0, -1):
        values[0], values[end] = values[end], values[0]
        sift_down(values, 0, end)
    return values


def sift_down(values, i, size):
    while True:
        largest = i
        left, right = 2 * i + 1, 2 * i + 2
        if left < size and values[left] > values[largest]:
            largest = left
        if right < size and values[right] > values[largest]:
            largest = right
        if largest == i:
            # the node already fits
            return
        values[i], values[largest] = values[largest], values[i]
        i = largest


print(heap_sort([4, 10, 3, 5, 1]))
#include <iostream>
#include <vector>

void siftDown(std::vector<int>& values, int i, int size) {
    while (true) {
        int largest = i;
        const int left = 2 * i + 1, right = 2 * i + 2;
        if (left < size && values[left] > values[largest])   largest = left;
        if (right < size && values[right] > values[largest]) largest = right;
        if (largest == i) return;     // the node already fits
        std::swap(values[i], values[largest]);
        i = largest;
    }
}

void heapSort(std::vector<int>& values) {
    const int n = static_cast<int>(values.size());
    for (int i = n / 2 - 1; i >= 0; --i) siftDown(values, i, n);
    for (int end = n - 1; end > 0; --end) {
        std::swap(values[0], values[end]);
        siftDown(values, 0, end);
    }
}

int main() {
    std::vector<int> values{4, 10, 3, 5, 1};
    heapSort(values);
    std::cout << '[';
    for (size_t i = 0; i < values.size(); i++) std::cout << (i ? ", " : "") << values[i];
    std::cout << "]\n";
}
import java.util.Arrays;

public class Main {
    static void siftDown(int[] values, int i, int size) {
        while (true) {
            int largest = i;
            int left = 2 * i + 1, right = 2 * i + 2;
            if (left < size && values[left] > values[largest])   largest = left;
            if (right < size && values[right] > values[largest]) largest = right;
            if (largest == i) return;  // the node already fits
            int tmp = values[i];
            values[i] = values[largest];
            values[largest] = tmp;
            i = largest;
        }
    }

    static void heapSort(int[] values) {
        int n = values.length;
        for (int i = n / 2 - 1; i >= 0; i--) siftDown(values, i, n);
        for (int end = n - 1; end > 0; end--) {
            int tmp = values[0];
            values[0] = values[end];
            values[end] = tmp;
            siftDown(values, 0, end);
        }
    }

    public static void main(String[] args) {
        int[] values = {4, 10, 3, 5, 1};
        heapSort(values);
        System.out.println(Arrays.toString(values));
    }
}
Watch it run

Step through it

Running on [4, 10, 3, 5, 1]

[4, 10, 3, 5, 1] read as a tree4040101101323253531414children of i: 2i + 1 and 2i + 2 · parent of i: (i - 1) // 2indexes 2, 3 and 4 are leaves, so they are already valid heaps
Step 1

The array is the tree

Heap sort never builds nodes. It reads the array as a complete binary tree: index i has children 2i + 1 and 2i + 2, and parent (i - 1) // 2. So 4 at index 0 is the root, 10 and 3 are its children, and 5 and 1 hang under 10. The two pictures are the same five values.

Output
1 / 13
4

Why Build-Heap Is O(n)

The obvious estimate is n sift-downs at O(log n) each, giving O(n log n). That bound is correct but not tight, and the real answer is O(n).

The reason is that most nodes are near the bottom, where sift down has almost nowhere to go. Half the nodes are leaves and cost nothing; a quarter sit one level up and cost at most one swap; an eighth cost at most two. Summing height × count over all levels gives Σ n/2^(h+1) · h, which converges to less than n.

Only the few nodes near the root can pay the full log n, and there are very few of them. So building the heap is Θ(n), and the O(n log n) total comes entirely from the extraction phase: n − 1 removals at O(log n) each. A complete answer states that split: Θ(n) to build, O(n log n) to extract.

Where the total cost actually comes from
PhaseOperationsCost eachTotal
Build heapn/2 sift downsO(log n) worst, O(1) typicalΘ(n)
Extractn−1 swaps + sift downsO(log n)Θ(n log n)
OverallΘ(n log n)
  • Half the nodes are leaves, so most sift-downs are free
  • Σ h · n / 2^(h+1) stays below n
5

Heap Sort vs Quick Sort

Both sort in place, and on paper heap sort looks better: O(n log n) guaranteed, against quick sort's O(n²) worst case. In practice quick sort is usually 2 to 3 times faster. Its partition scans memory left to right, which the CPU cache handles well, while sift down jumps from index i to 2i + 1 across the array, missing the cache on large inputs.

It earns its place as a safety net. Introsort, used by C++ std::sort, runs quick sort and switches to heap sort if the recursion gets too deep, keeping quick sort's speed with an O(n log n) guarantee. It also suits systems that need a hard time bound with no extra memory.

Neither is stable. When equal keys must keep their order, use merge sort, at the cost of O(n) extra space. The sorting algorithms lesson compares all the common sorts, and the heap itself is practised in Kth Largest Element in an Array.

Heap sort vs quick sort vs merge sort
Heap sortQuick sortMerge sort
Worst caseO(n log n)O(n²)O(n log n)
AverageO(n log n)O(n log n), fastest in practiceO(n log n)
Extra spaceO(1)O(log n) stackO(n)
StableNoNoYes
Memory accessScatteredSequentialSequential
  • Quick sort wins on speed, heap sort on guarantees
  • Introsort combines them
  • Need stability? Merge sort