Post

Heap Sort in Java

Learn how Heap Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.

Heap Sort in Java

Introduction

Heap Sort is a comparison sort built on a data structure called a binary heap. It first rearranges the array into a heap, so that the largest value sits at the front, and then repeatedly moves that largest value to the end of the array and repairs the heap for the values that are left.

Three ideas carry the whole algorithm:

  • Max-heap: a binary tree, stored in the array itself, where every parent is greater than or equal to its children. The largest value is always at the root.
  • Sift down: move a value down the tree, swapping it with its larger child, until it is no smaller than either child. This repairs the heap.
  • Extract the maximum: swap the root with the last value of the heap, shrink the heap by one, and sift the new root down.

Heap Sort guarantees $O(n \log n)$ in every case and sorts in place, with no extra array. That makes it a useful fallback: introsort, the algorithm behind C++ std::sort, switches from QuickSort to Heap Sort when the recursion gets too deep. Heaps on their own are just as important, as the structure behind Java’s PriorityQueue.

This article uses a bottom-up heap build with a 1-based heap index: the heap positions are numbered from 1 to n, and every array access subtracts one.

Performance Characteristics

Heap Sort runs in the same time whatever the input looks like and needs no extra memory, but it does more work per element than QuickSort and is not stable.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

CaseTimeWhen it happens
Best$O(n \log n)$Any input with distinct values, even an array that is already sorted
Average$O(n \log n)$Random or mixed input
Worst$O(n \log n)$Any input: the heap is always a balanced tree

Why $n \log n$? A heap with $n$ values is a balanced tree about $\log_2 n$ levels deep, so one sift down takes at most $\log n$ swaps. The sort extracts the maximum $n - 1$ times, each followed by one sift down. Building the heap at the start is cheaper than it looks: it takes only $O(n)$, because most values sit near the bottom of the tree and have little distance to move.

Heap Sort’s guarantee is its strength, but in practice it is usually slower than QuickSort. Sift down jumps between a parent at k and children at 2k, which is far apart in memory for large arrays and makes poor use of the CPU cache.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(1)$: the heap lives inside the array, and sift down is a loop
In placeYes
StableNo (swapping the root to the end can jump over equal values)

Algorithm (Pseudo Code)

Heap Sort treats the array as a binary tree: the first value is the root, and the value at position k has its children at positions 2k and 2k + 1. To turn the array into a max-heap, it visits every parent from the last one back to the root, and sifts each one down: if the parent is smaller than its larger child, the two swap, and the value keeps moving down until it is no smaller than its children. When the root has been sifted down, every parent is at least as large as its children, so the largest value is at the root.

Now the sorting starts. The root holds the largest value, so it is swapped with the last value of the heap, which is exactly where the largest value belongs. The heap shrinks by one, so that the sorted value at the end is left alone, and the new root is sifted down to repair the heap. The next largest value then sits at the root, and the same steps repeat until only one value is left in the heap.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
sort(array):
    n = length of array
    heapify(array, n)
    while n > 1:
        swap(array[1], array[n])           // largest value to the end
        n = n - 1
        siftDown(array, 1, n)
    return array

heapify(array, n):
    for k = n / 2 down to 1:              // every parent, last one first
        siftDown(array, k, n)

siftDown(array, k, n):                    // positions are 1-based
    while 2k <= n:                        // k has at least one child
        j = 2k                            // left child
        if j < n and array[j] < array[j + 1]:
            j = j + 1                     // right child is larger
        if not array[k] < array[j]:
            break                         // heap property holds
        swap(array[k], array[j])
        k = j

After every sift down in the sorting loop, array[1 .. n] is a valid max-heap, and array[n + 1 ..] holds the largest values in sorted order.

The positions in the pseudo code start at 1, because that makes the children of k simply 2k and 2k + 1. The Java code keeps that numbering and subtracts one whenever it reads or swaps an array element, so position k is array[k - 1].

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.

Each step shows the heap as a tree, the same values in the array and the line of code that is running, with a short explanation of what just happened:

  • Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
  • Play: press Play to run the steps automatically, and press it again to pause.
  • Shuffle: press the shuffle button to start again with a new random order.
  • Pointers: K is the node being sifted down, and J is its larger child. In the tree, they are marked with a coloured ring.
  • Colours: the two values being compared are amber, the two values being swapped are salmon, and values in their final position turn green.
  • Tree: the tree and the array show the same values. A node’s array index is one less than its heap position k.
  • Heap boundary: the gray bar marks the end of the heap. Everything to its right is sorted and no longer part of the tree.
compared swap final position K = k J = larger child

Java Code

The implementation is a HeapSort class with one public method, sort, and two private methods: heapify turns the array into a max-heap, and siftDown moves one value down the tree until the heap property holds. Two small helpers, less and swap, live in a separate SortUtils class.

The complete code is in the algorithm-examples repository on GitHub: HeapSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
7
8
9
10
11
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    int n = array.length;
    heapify(array, n);
    while (n > 1) {
        SortUtils.swap(array, 0, n - 1);
        n--;
        siftDown(array, 1, n);
    }
    return array;
}

sort is the entry point. It accepts an array of any Comparable type, such as Integer or String, and first calls heapify to turn the whole array into a max-heap. Then, while the heap holds more than one value, it swaps the root at index 0 with the last value of the heap at index n - 1, shrinks the heap by one, and calls siftDown on the new root. It returns the same array, now sorted.

n does double duty: it is the size of the heap, and also the index where the sorted part of the array begins. The swap uses array indices directly, 0 and n - 1, while siftDown is called with heap position 1 for the root.

heapify

1
2
3
4
5
private <T extends Comparable<T>> void heapify(final T[] array, final int n) {
    for (int k = n / 2; k >= 1; k--) {
        siftDown(array, k, n);
    }
}

heapify builds the max-heap from the bottom up. Heap position n / 2 is the last node that has a child, so every position after it is a leaf, and a leaf on its own is already a valid heap. Working backwards from n / 2 to the root, each sift down joins a parent with two children that are already heaps, so when the loop reaches position 1 the whole array is a heap.

Many textbooks use the name “heapify” for the sift-down step itself. In this code, heapify is the loop that builds the whole heap, and siftDown is the step that repairs one node.

siftDown

1
2
3
4
5
6
7
8
9
10
11
12
13
private <T extends Comparable<T>> void siftDown(final T[] array, int k, final int n) {
    while (2 * k <= n) {
        int j = 2 * k;
        if (j < n && SortUtils.less(array[j - 1], array[j])) {
            j++;
        }
        if (!SortUtils.less(array[k - 1], array[j - 1])) {
            break;
        }
        SortUtils.swap(array, k - 1, j - 1);
        k = j;
    }
}

siftDown does the real work. k is a heap position, numbered from 1, so its left child is at 2 * k and its right child at 2 * k + 1. While k has at least one child, j starts at the left child and moves to the right child if that one is larger. If the value at k is not smaller than its larger child, the heap property holds and the loop stops. Otherwise the two swap, and k moves down to the child’s position to carry on.

Two details are worth noticing:

  • Every array access subtracts one: heap position k is array[k - 1], and the right child, at position j + 1, is array[j]. That is why the code compares array[j - 1] with array[j] to pick the larger child.
  • j < n checks that a right child exists. When 2 * k == n, the node has only a left child, so there is nothing to compare it with.

less and swap

1
2
3
4
5
6
7
8
9
10
11
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) < 0;
}

public static <T> void swap(T[] array, int i, int j) {
    if (i != j) {
        final T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

These two helpers from SortUtils keep siftDown easy to read. less returns true when the first element is smaller than the second, using compareTo, so the algorithm works for any type that implements Comparable. swap exchanges two elements, and skips the work when both indices are the same.

Running it

1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new HeapSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a HeapSort, pass it an array, and the same array comes back sorted. The array holds Integer, not int, because the method works with Comparable objects.

Summary

  • Heap Sort is a comparison sort built on a binary max-heap, stored inside the array itself.
  • This implementation builds the heap bottom-up with heapify, then repeatedly swaps the root to the end and sifts the new root down, using a 1-based heap position k for array[k - 1].
  • After each extraction, array[0 .. n - 1] is a max-heap and everything after it holds the largest values in sorted order.
  • It runs in $O(n \log n)$ in the best, average and worst case, and needs only $O(1)$ extra space.
  • It sorts in place but is not stable, and it is usually slower than QuickSort in practice. Choose it when you need a guaranteed $O(n \log n)$ without extra memory; choose Merge Sort when you need stability.
This post is licensed under CC BY 4.0 by the author.