Heap Sort, step by step.

Heap sort is an in-place sorting algorithm that turns an array into a max heap, then repeatedly swaps the root, the largest value, to the end of the heap and sifts the new root down, so the sorted part grows from the right. It takes O(n log n) time even in the worst case, needs O(1) extra space and is not stable. This page explains how it works, with step-by-step animations of building the max heap, the first extractions and the remaining extractions from the VisiGrab app.

How heap sort works

What is heap sort?

Heap sort is an in-place sorting algorithm that turns an array into a max heap, a binary tree stored in the array with the largest value at the root. It then repeatedly swaps the root to the end and repairs the smaller heap. It takes O(n log n) time even in the worst case and O(1) extra space, and it is not stable. J. W. J. Williams invented it in 1964, and Robert W. Floyd added the O(n) heap build that year.

How heap sort works: a max heap inside the array

The tree is the array itself, read level by level: index 0 is the root, and the children of index i sit at 2i + 1 and 2i + 2, as in a min heap. A max heap is the mirror image of a min heap: no child is larger than its parent.

The array 3, 10, 7, 8, 2, 6, 1, 4, 5, 9 as a column of cells with indices 0 to 9, beside the binary tree it stands for: 3 at the root; 10 and 7 below it; under 10 are 8 and 2, under 7 the leaves 6 and 1; under 8 the leaves 4 and 5, and under 2 the leaf 9. Every node carries its index. The root has a color of its own, and each pair of siblings shares one color in both the column and the tree: 10 and 7, 8 and 2, 6 and 1, 4 and 5, and 9, an only child.
The children of index i sit at 2i + 1 and 2i + 2, so each color pair is the two children of one node: 10 and 7 are the root's, and 9 is node 4's only child. Indices 5 to 9 are leaves.

First the sort builds the max heap. Then each extraction swaps the root, the largest value left, with the heap's last node, its final place. The heap shrinks by one, and the new root sifts down (the app's code calls this heapify): it trades places with its larger child until neither child is larger. The sorted part grows from the right, so ascending order needs a max heap; a min heap would sort in descending order.

For ten values, index 4 (n/2 − 1) is the last node with a child, and indices 5 to 9 are leaves: with no children, they already satisfy the heap condition. The build sifts down nodes 4, 3, 2, 1 and 0 in that order, so by a node's turn both subtrees below it are heaps.

Heap sort pseudocode: heapify with a hole

Textbooks sift down with a swap per level. The app's heapify does it with a hole: when a child is larger, it copies the value into a temporary variable, so its node becomes a hole that may be overwritten. While the larger child is larger than this stored value, the child's value moves up into the hole, and the hole moves down. Then the stored value is pasted into the last hole: one write per level instead of a swap's three.

In pseudocode:

heapSort(a)
    n = length of a
    buildHeap(a, n)
    for i from n - 1 down to 1
        swap a[0] and a[i]
        heapify(a, 0, i)

buildHeap(a, size)
    for i from size / 2 - 1 down to 0
        heapify(a, i, size)

heapify(a, i, size)
    examined = a[i]
    while i < size / 2
        c = largestChild(a, i, size)
        if examined >= a[c]
            stop
        a[i] = a[c]
        i = c
    a[i] = examined

largestChild(a, i, size)
    l = 2 * i + 1
    r = l + 1
    if r < size and a[l] < a[r]
        return r
    return l

The names are the app's: heapSort, buildHeap, heapify and, shortened here, largestChild for its getLargestChildIndex. largestChild returns the left child unless the right one is inside the heap and larger, so a tie goes left. heapify copies a[i] into examined, the stored value. While i has a child (i < size / 2), it compares examined with the larger child c: if examined >= a[c], an equal child included, it stops; otherwise the child's value moves up and i moves down to c, the hole. Then examined fills the hole. / rounds down. buildHeap heapifies nodes size / 2 - 1 down to 0. In heapSort, the swap moves the root to a[i], the heap's last cell, and heapify(a, 0, i) repairs a[0..i - 1]. The app's code also shows a recursive heapify that swaps instead.

Heap sort example: building the max heap

The player builds a max heap from the app's default array, 3, 10, 7, 8, 2, 6, 1, 4, 5, 9, sifting down nodes 4 to 0. A checked node turns yellow, then green if it satisfies the heap condition or red if a child is larger. The max heap is 10, 9, 7, 8, 3, 6, 1, 4, 5, 2.

Building the max heap

All steps as text
  1. Sort the array using the Heap Sort algorithm.
  2. Represent the array as a binary tree.
  3. Transform the binary tree into a max heap, ensuring each parent node is greater than its children.
  4. Mark leaf nodes green, since they inherently satisfy heap properties.
  5. Focus on the node at index 4 and check if it meets the max heap condition.
  6. Mark the node red for adjustment since its child’s value is greater.
  7. Temporarily store the current node’s value to replace it later.
  8. Replace this node's value with the value of its larger child.
  9. Examine the node at index 9.
  10. Since this node has no children, paste the stored value here.
  11. Focus on the node at index 3 and check if it meets the max heap condition.
  12. Mark the node green, as it satisfies the heap condition with its children.
  13. Focus on the node at index 2 and check if it meets the max heap condition.
  14. Mark the node green, as it satisfies the heap condition with its children.
  15. Focus on the node at index 1 and check if it meets the max heap condition.
  16. Mark the node green, as it satisfies the heap condition with its children.
  17. Focus on the node at index 0 and check if it meets the max heap condition.
  18. Mark the node red because it has a child with a higher value.
  19. Temporarily store the current node’s value to replace it later.
  20. Replace the node’s value with the value of its largest child.
  21. Examine the node at index 1. Its largest child’s value exceeds the stored value.
  22. Replace the current node’s value with the value of its largest child.
  23. Examine the node at index 4. Since the stored value is not less than its largest child, the stored value needs to be pasted here.
  24. Paste the stored value; the tree now satisfies heap properties.
  25. The max heap is built: 10, 9, 7, 8, 3, 6, 1, 4, 5, 2. Building it made 12 comparisons (7 with the larger child, 5 between two children) and three moves up.
Heap Sort — Building the max heap. Last step: The max heap is built: 10, 9, 7, 8, 3, 6, 1, 4, 5, 2. Building it made 12 comparisons (7 with the larger child, 5 between two children) and three moves up.

Building from the bottom up costs O(n), as most nodes sit near the bottom and sift down few levels; the min heap page shows why.

Heap sort example: the first extractions

Each extraction swaps the root with the last node of the heap; that node, now holding the maximum, leaves the tree for the sorted part, and the new root sifts down. The player extracts 10, 9 and 8, and each time the same value, 2, comes up to the root and sinks again. The heap is then 7, 5, 6, 4, 3, 2, 1, followed by 8, 9 and 10.

The first extractions

All steps as text
  1. The array is now a max heap: 10, 9, 7, 8, 3, 6, 1, 4, 5, 2. Its root holds the largest value, 10.
  2. Swap the root node with the last node in the heap. The element with value 10 is now fixed in its final position.
  3. Reduce the heap size by excluding the last node.
  4. Focus on the node at index 0 and check if it meets the max heap condition.
  5. Mark the node red because it has a child with a higher value.
  6. Temporarily store the current node’s value to replace it later.
  7. Replace the node’s value with the value of its largest child.
  8. Examine the node at index 1. Its largest child’s value exceeds the stored value.
  9. Replace the current node’s value with the value of its largest child.
  10. Examine the node at index 3. Its largest child’s value exceeds the stored value.
  11. Replace the current node’s value with the value of its largest child.
  12. Examine the node at index 8.
  13. Since the node has no children, paste the stored value here to restore heap property.
  14. Swap the root node with the last node in the heap. The element with value 9 is now fixed in its final position.
  15. Reduce the heap size by excluding the last node.
  16. Focus on the node at index 0 and check if it meets the max heap condition.
  17. Mark the node red because it has a child with a higher value.
  18. Temporarily store the current node’s value to replace it later.
  19. Replace the node’s value with the value of its largest child.
  20. Examine the node at index 1. Its largest child’s value exceeds the stored value.
  21. Replace the current node’s value with the value of its largest child.
  22. Examine the node at index 3. Its largest child’s value exceeds the stored value.
  23. Replace the node’s value with its child’s value.
  24. Examine the node at index 7.
  25. Since the node has no children, paste the stored value here to restore heap property.
  26. Swap the root node with the last node in the heap. The element with value 8 is now fixed in its final position.
  27. Reduce the heap size by excluding the last node.
  28. Focus on the node at index 0 and check if it meets the max heap condition.
  29. Mark the node red because it has a child with a higher value.
  30. Temporarily store the current node’s value to replace it later.
  31. Replace the node’s value with the value of its largest child.
  32. Examine the node at index 2. Its largest child’s value exceeds the stored value.
  33. Replace the current node’s value with the value of its largest child.
  34. Examine the node at index 5.
  35. Since the node has no children, paste the stored value here to restore heap property.
  36. Three root swaps put 10, 9 and 8 in their final places. The sift-downs made 15 comparisons (8 with the larger child, 7 between two children) and eight moves up. The heap is now 7, 5, 6, 4, 3, 2, 1.
Heap Sort — The first extractions. Last step: Three root swaps put 10, 9 and 8 in their final places. The sift-downs made 15 comparisons (8 with the larger child, 7 between two children) and eight moves up. The heap is now 7, 5, 6, 4, 3, 2, 1.

Heap sort example: the remaining extractions

The player extracts 7, 6, 5, 4, 3 and 2 the same way. The last value, 1, is already in place, and the column becomes a sorted row again.

The remaining extractions

All steps as text
  1. 10, 9 and 8 are in their final places. The heap holds 7, 5, 6, 4, 3, 2, 1.
  2. Swap the root node with the last node in the heap. The element with value 7 is now fixed in its final position.
  3. Reduce the heap size by excluding the last node.
  4. Focus on the node at index 0 and check if it meets the max heap condition.
  5. Mark the node red because it has a child with a higher value.
  6. Temporarily store the current node’s value to replace it later.
  7. Replace the node’s value with the value of its largest child.
  8. Examine the node at index 2. Its largest child’s value exceeds the stored value.
  9. Replace the node’s value with its child’s value.
  10. Examine the node at index 5.
  11. Since the node has no children, paste the stored value here to restore heap property.
  12. Swap the root node with the last node in the heap. The element with value 6 is now fixed in its final position.
  13. Reduce the heap size by excluding the last node.
  14. Focus on the node at index 0 and check if it meets the max heap condition.
  15. Mark the node red because it has a child with a higher value.
  16. Temporarily store the current node’s value to replace it later.
  17. Replace the node’s value with the value of its largest child.
  18. Examine the node at index 1. Its largest child’s value exceeds the stored value.
  19. Replace the current node’s value with the value of its largest child.
  20. Examine the node at index 3.
  21. Since the node has no children, paste the stored value here to restore heap property.
  22. Swap the root node with the last node in the heap. The element with value 5 is now fixed in its final position.
  23. Reduce the heap size by excluding the last node.
  24. Focus on the node at index 0 and check if it meets the max heap condition.
  25. Mark the node red because it has a child with a higher value.
  26. Temporarily store the current node’s value to replace it later.
  27. Replace the node’s value with the value of its largest child.
  28. Examine the node at index 1. Since the stored value is not less than its largest child, the stored value needs to be pasted here.
  29. Paste the stored value; the tree now satisfies heap properties.
  30. Swap the root node with the last node in the heap. The element with value 4 is now fixed in its final position.
  31. Reduce the heap size by excluding the last node.
  32. Focus on the node at index 0 and check if it meets the max heap condition.
  33. Mark the node red because it has a child with a higher value.
  34. Temporarily store the current node’s value to replace it later.
  35. Replace the node’s value with the value of its largest child.
  36. Examine the node at index 1.
  37. Since the node has no children, paste the stored value here to restore heap property.
  38. Swap the root node with the last node in the heap. The element with value 3 is now fixed in its final position.
  39. Reduce the heap size by excluding the last node.
  40. Focus on the node at index 0 and check if it meets the max heap condition.
  41. Mark the node green, as its value is greater than its child’s and heap property holds.
  42. Swap the root node with the last node in the heap. The element with value 2 is now fixed in its final position.
  43. Reduce the heap size for the next step.
  44. Leave the last remaining item in place, as it is already in its correct position.
  45. The entire array is now sorted.
  46. Six more root swaps put 7, 6, 5, 4, 3 and 2 in place, with 13 comparisons (8 with the larger child, 5 between two children) and six moves up. The whole sort made 40 comparisons, 17 moves up and nine root swaps.
Heap Sort — The remaining extractions. Last step: The array is sorted: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.

Why does heap sort use a max heap?

Because the heap shrinks from the right: each extraction frees its last cell, which in ascending order belongs to the largest value left, the root; a min heap would sort in descending order. The second player shows the first such swap at step 2.

Is heap sort stable?

No. A root swap can carry a value past an equal one; the example below shows how.

Why is heap sort O(n log n)?

Because it makes n − 1 sift-downs, and a heap is a complete binary tree: n values fill only about log2 n levels (ten values fill four), so no sift-down can go deeper, whatever the input.

Heap sort time and space complexity

After the O(n) build, n − 1 sift-downs each descend at most log2 n levels, so heap sort takes O(n log n) even in the worst case. Each level costs two comparisons, child against child and stored value against the larger child: at worst about 2n log2 n. The default array takes 40: 12 to build and 28 to sort.

CaseComparisons, ten valuesTimeExtra space
Best: all values equal24O(n)O(1)
Best: distinct values31O(n log n)O(1)
Average38.6O(n log n)O(1)
Worst44O(n log n)O(1)

When all values are equal, every sift-down stops at its first check. Heap sort is not adaptive: sorted input is no faster. 1 to 10 in ascending order takes 41 comparisons, as the build lifts every large value to the top. Descending input is already a max heap, since each parent comes before its children and is larger. The build moves nothing, yet the extractions still make 26 comparisons: 35 in all.

Heap sort is in-place: the heap and the sorted part share the array, so the extra memory is the stored value and a few indices.

Bottom-up heap sort

The value swapped to the root comes from the bottom of the heap, so it is usually small: here always 1, 2 or 3. In six of the example's eight sift-downs, it sinks to a leaf. Bottom-up heap sort therefore moves the hole straight down to a leaf, one comparison per level, and then lets the stored value climb back up: about n log2 n comparisons on average instead of 2n log2 n. GCC's and LLVM's C++ libraries, Python's heapq and the Linux kernel sift this way.

Why heap sort is not stable

A stable sort keeps equal values in their original order. A root swap can carry a value past its equals. 2a, 2b, 1 is already a max heap, since 2a is not smaller than its larger child 2b. The first swap sends 2a to the end, behind 2b. 2b rises in the sift-down, and the second swap puts it back at index 1: 1, 2b, 2a.

Four columns of three cells, read from top to bottom and labeled Max heap, Swap 1, Heapify and Swap 2. The max heap holds a 2 marked a, a 2 marked b, and 1. After swap 1 the column is 1, the 2 marked b, the 2 marked a, with a bracket labeled sorted beside the bottom cell. After heapify it is the 2 marked b, 1, the 2 marked a. After swap 2 it is 1, the 2 marked b, the 2 marked a, with the bracket beside the bottom two cells: the two equal 2s have changed order.
Swap 1 sends the first 2 to the end, past the second, and nothing brings it back: the equal values end in reversed order, so heap sort is not stable.

Sorting pairs of value and original index makes it stable, at the cost of O(n) extra memory.

Heap sort vs selection sort, quick sort and merge sort

Heap sort is selection sort with a heap: each step still selects one value, the largest left, but in O(log n) instead of an O(n) scan. On selection sort's array 5, 2, 1, 4, 0, 6, 3, heap sort makes 20 comparisons and selection sort 21.

Quick sort is often two to three times faster than heap sort, as it reads memory in order; sift-down jumps from i to 2i + 1 and misses the cache on large arrays. But quick sort can degrade to O(n2), and merge sort, though stable, needs O(n) extra memory. Of the three, only heap sort guarantees O(n log n) in O(1) space, as the merge sort page shows.

Heap sort in Python, Java and C++

The app shows the code in all three: an iterative heapify that fills the hole and a recursive one that swaps. The standard libraries differ.

Note

C++ has heap sort built in: std::make_heap builds a max heap, and std::sort_heap sorts it in place into ascending order.

Note

Python's heapq is a min heap, and the heapsort example in its documentation builds new lists: O(n) extra memory, and, as the docs say, not stable. Python 3.14 added max heap functions such as heapq.heapify_max.

Note

Java has no public heap sort method. PriorityQueue is a min heap: polling it once per value gives ascending order, but the queue is a copy that takes O(n) extra memory.

The full source code is on GitHub, in Python, Java and C++.

When heap sort is used

Heap sort suits:

  • Memory- and time-bound code: O(n log n) guaranteed in O(1) extra memory, without recursion. The Linux kernel's sort() is a heap sort for this reason, and the app's info dialog names real-time data processing.
  • A fallback, not a default, in library sorts: introsort runs quick sort and switches to heap sort when the recursion gets too deep. C++'s std::sort does this in GCC and LLVM, and since Java 14 so does Arrays.sort for int, long, float and double arrays. Python's sort never uses heap sort.
  • The k largest values: stop after k extractions, in O(n + k log n).

Three animations here.
The whole topic in the app.

In VisiGrab heap sort runs on the default, a random or your own array of ten values, with a step for every check, stored value, move, paste and root swap: 101 steps on the default array.

Your own array

Random picks ten distinct values from 0 to 19. Custom opens a ten-cell dialog for values from 0 to 99, equal ones included, with buttons for an ascending fill, which takes 117 steps, or a descending one, which takes 87. Equal values show the tie rules at work.

Forward and back

Step forward and back through every check, red mark, store, move, paste, swap and shrink, each with its message. The last random or custom array comes back next time.

Theory and complexity

Two tabs. Info covers the two phases, what a max heap is, the characteristics (in-place with O(1) auxiliary space, unstable, not adaptive), O(n log n) in every case and a fit for real-time data processing. Details pairs an array fragment with its tree, then explains building the heap from the last non-leaf node and the sorting phase.

Python, Java and C++

The heapSort, buildHeap, heapify and getLargestChildIndex methods in Java and heap_sort, build_heap, heapify and get_largest_child_index in Python and C++, plus a recursive heapify that swaps, with links to the full source on GitHub. After the last step, a hint points to the code.

Quiz

Eight questions with an explanation for every answer, from why heap sort builds a max heap to how fast it runs on an array that is already sorted.

Five more sorts and a heap

Bubble, selection, insertion, merge and quick sort each have a topic of their own, and the Heap topic builds a min heap step by step.

Sort an array
one root at a time.

Download VisiGrab and step through every sift-down and root swap, on the default array, a random one or an array of your own.

Heap sort is one of 30+ topics. See them all