Heap Sort

Sort an array in place by building a max-heap inside it and moving its largest value to the end, one value at a time.

Sort an array of integers from smallest to largest with heap sort. The values must be rearranged inside the array itself, without copying them into a second array.

Example
Input: [4, 10, 3, 5, 1]
Output: [1, 3, 4, 5, 10]
Solution

The Idea

Suppose a helper could always hand you the largest number still left in [4, 10, 3, 5, 1]. Sorting would be easy: ask for the largest and put it in the last slot, then ask again and fill the slot before it. The helper gives 10, 5, 4, 3 and 1, and filling from the back gives [1, 3, 4, 5, 10]. So the real question is how to build such a helper inside the array, with no second array.

The helper comes from reading the array as a tree. Index 0 sits at the top. Indexes 1 and 2 hang below it, and indexes 3 and 4 hang below index 1. In general, the value at index i has the values at 2i + 1 and 2i + 2 below it. A value with values below it is their parent, and they are its children.

The picture below follows the array through the whole sort. In the row labelled "start", the tree on the right shows 4 at the top with children 10 and 3, and 10 with children 5 and 1. Nothing is in order yet.

Heap sort on [4, 10, 3, 5, 1], one row per step. Start: [4, 10, 3, 5, 1]. Heap built: [10, 5, 3, 4, 1] with 10 at the top. Then 10, 5, 4 and 3 are moved to the end one by one, each time leaving a smaller heap at the front, until the array reads [1, 3, 4, 5, 10].

Now rearrange the values so that every parent is at least as large as its children. Look at the row labelled "heap built": 10 is above 5 and 3, and 5 is above 4 and 1. A tree that keeps this rule is called a max-heap. The rule passes down every level, so the top of the tree, called the root, holds the largest value. That is the helper.

Taking the largest value out is a single swap. In the row labelled "10 moved to the end", 10 traded places with the last value of the heap, 1, and it now sits at index 4, where it belongs. The heap shrinks to indexes 0 to 3. Then 1, which is too small for the root, moves down: it swaps with its larger child 5, then with 4. Moving a value down like this, always swapping with the larger child, is called sifting down.

The next rows repeat the same move. The boxes at the back, orange for the value just moved and teal for the ones before it, grow by one each time, while the blue heap at the front shrinks by one. When the heap holds only 1, the array is sorted. Both parts share the one array the whole time, so heap sort needs no second array.

Solution Approach

The plan raises four questions: why a heap beats searching for the largest value, how to turn the array into a heap, how to repair it after each swap, and what happens to equal values.

Finding the largest value quickly

Why build a heap at all? The simple way is to scan the unsorted part for its largest value, move it to the back, and scan again. That is correct, but the scans look at about n + (n - 1) + ... + 1 values, roughly n²/2, for an array of n values. With a heap, the largest value is already at the root, and repairing the heap after a swap only walks one path from the root down. That path has about log₂ n steps, so for 1,024 values a sift-down makes at most 10 swaps.

Building the heap from the bottom up

Where should the building start? The values at the bottom of the tree have no children, so each of them already obeys the rule. In an array of n values, the last parent sits at index n / 2 - 1, and every index after it has no children. So the build sifts down each parent, starting at the last one and going back to index 0.

For [4, 10, 3, 5, 1], n is 5 and the parents are at indexes 1 and 0. Index 1 holds 10, which is larger than its children 5 and 1, so it stays. Index 0 holds 4, which swaps with its larger child 10 and then with 5. That gives [10, 5, 3, 4, 1], the row labelled "heap built". Going from the bottom up means that both trees under a parent are already heaps when the parent is sifted, so one sift-down is enough.

Repairing the heap after each swap

After the root is swapped to the end, what is broken? Only the root: the value that came from the end now sits on top of two smaller trees that are still heaps. Sifting it down fixes that. It compares itself with both children, swaps with the larger one, and keeps going until no child is larger or there are no children left.

Why the larger child? Right after 10 left the root, 1 sat above 5 and 3, before it sifted down to the place shown in the row labelled "10 moved to the end". Swapping with 5 puts 5 above 3, which is fine. Swapping with 3 would have put 3 above 5, and the rule would break again. The sift-down also needs to know where the heap ends. At that moment the heap is indexes 0 to 3, so 10 at index 4 is not a child of anyone any more.

Equal values

What happens when two values are equal? For plain integers, nothing you can see. It matters when you sort records by one field. Take three cards, 2a, 2b and 1c, sorted by their number only. A sort that keeps 2a before 2b, as in the input, is called stable. Running the same heap sort on these cards gives [1c, 2b, 2a]. Building the heap moves no card, and then the first swap sends 2a from the root to the last slot, past 2b. So heap sort is not stable.

Java Solution

The method sort works in these steps:

  1. First, store the length of the array in n. A helper, siftDown(arr, size, i), moves the value at index i down inside the heap arr[0..size-1]; steps 4 and 5 show how.
  2. Build the heap with a loop that moves i from n / 2 - 1 back to 0 and calls siftDown(arr, n, i) for each parent.
  3. Then a second loop moves end from n - 1 down to 1. Each time, swap(arr, 0, end) puts the largest value at index end, and siftDown(arr, end, 0) repairs the heap, which is now the first end values.
  4. Inside siftDown, a while loop sets largest to i and works out the child indexes left and right. Each child that lies inside the heap and is bigger than arr[largest] takes over largest.
  5. If largest is still i, the value is in place and the method returns. Otherwise it swaps the two values and carries on from the child's index. Using a loop here instead of a method that calls itself keeps the extra memory constant.

The main method sorts the example, a second mixed array, an empty array, a single value, repeats with negatives, an already sorted array, and the largest and smallest int values together.

Java
import java.util.Arrays;

public class HeapSort {

    public static void sort(int[] arr) {
        int n = arr.length;
        // build a max-heap: sift down every parent, the last parent first
        for (int i = n / 2 - 1; i >= 0; i--) {
            siftDown(arr, n, i);
        }
        // move the largest value (the root) behind the heap, shrink the heap, repair it
        for (int end = n - 1; end > 0; end--) {
            swap(arr, 0, end);
            siftDown(arr, end, 0);
        }
    }

    // Moves arr[i] down until it is at least as large as its children; the heap is arr[0..size-1]
    private static void siftDown(int[] arr, int size, int i) {
        while (true) {
            int largest = i;
            int left = 2 * i + 1;
            int right = 2 * i + 2;
            if (left < size && arr[left] > arr[largest]) {
                largest = left;
            }
            if (right < size && arr[right] > arr[largest]) {
                largest = right;
            }
            if (largest == i) {
                return;                       // both children are smaller: done
            }
            swap(arr, i, largest);
            i = largest;                      // keep going from the child's old place
        }
    }

    private static void swap(int[] arr, int a, int b) {
        int tmp = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp;
    }

    public static void main(String[] args) {
        int[][] inputs = {
            {4, 10, 3, 5, 1},
            {12, 11, 13, 5, 6, 7},
            {},
            {42},
            {3, -1, 3, 0, -1, 3},
            {1, 2, 3, 4, 5, 6},
            {Integer.MAX_VALUE, -7, Integer.MIN_VALUE, 0}
        };
        for (int[] data : inputs) {
            String before = Arrays.toString(data);
            sort(data);
            System.out.println(before + " -> " + Arrays.toString(data));
        }
    }
}

Running it prints:

Output
[4, 10, 3, 5, 1] -> [1, 3, 4, 5, 10]
[12, 11, 13, 5, 6, 7] -> [5, 6, 7, 11, 12, 13]
[] -> []
[42] -> [42]
[3, -1, 3, 0, -1, 3] -> [-1, -1, 0, 3, 3, 3]
[1, 2, 3, 4, 5, 6] -> [1, 2, 3, 4, 5, 6]
[2147483647, -7, -2147483648, 0] -> [-2147483648, -7, 0, 2147483647]

The top line sorts [4, 10, 3, 5, 1] into [1, 3, 4, 5, 10], the same array as the last row of the picture. The empty array and [42] come back unchanged: with n at 0 or 1, both loops stop before their first round. The line with repeats shows the two -1 values and the three 3 values next to each other, [-1, -1, 0, 3, 3, 3].

Look at the last line. It sorts Integer.MAX_VALUE and Integer.MIN_VALUE correctly because siftDown compares with >. A version that tests arr[left] - arr[largest] > 0 instead goes wrong: 2,147,483,647 minus -2,147,483,648 does not fit in an int and wraps around to a negative number. Run on the same four values, that version printed [-7, 0, 2147483647, -2147483648].

Complexity

Building the heap happens once, then each of the n - 1 values moved to the end costs one swap and one sift-down.

  • Time: O(n log n) in the average and worst case, because each of the n - 1 sift-downs after a swap can walk about log₂ n steps from the root to the bottom. The bottom-up build adds only O(n), since most parents sit just one or two levels above the bottom.
  • Best case: O(n), when all values are equal, because every sift-down stops after comparing the value with its children once.
  • Space: O(1), because the heap and the sorted part share the input array and siftDown keeps only three indexes.

A count of the comparisons for 1,024 values shows how little the order of the input matters. An already sorted array took 18,060 comparisons, a reverse sorted one 16,407, and random values (seed 42) 17,338. Only an array of equal values stood out, at 3,066. The reverse sorted array is already a max-heap, so its build swaps nothing, but every value still has to be moved out and sifted down.

Java's Arrays.sort for an int[] makes use of that steady O(n log n) with no extra memory. In JDK 25 it sorts with a quicksort variant, and switches a part of the array to heap sort when the quicksort recursion on it gets too deep.