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
Output: [1, 3, 4, 5, 10]
The Idea
Suppose a helper could always hand you the largest number still left in [4, 10, 3, 5, 1][1, 3, 4, 5, 10]
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 i2i + 12i + 2
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.
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][10, 5, 3, 4, 1]
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]
Java Solution
The method sort
- First, store the length of the array in
. A helper,n , moves the value at indexsiftDown(arr, size, i) down inside the heapi ; steps 4 and 5 show how.arr[0..size-1] - Build the heap with a loop that moves
fromi back to 0 and callsn / 2 - 1 for each parent.siftDown(arr, n, i) - Then a second loop moves
fromend down to 1. Each time,n - 1 puts the largest value at indexswap(arr, 0, end) , andend repairs the heap, which is now the firstsiftDown(arr, end, 0) values.end - Inside
, asiftDown loop setswhile tolargest and works out the child indexesi andleft . Each child that lies inside the heap and is bigger thanright takes overarr[largest] .largest - If
is stilllargest , 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.i
The mainint
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:
[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][1, 3, 4, 5, 10][42][-1, -1, 0, 3, 3, 3]
Look at the last line. It sorts Integer.MAX_VALUEInteger.MIN_VALUEsiftDown>arr[left] - arr[largest] > 0int[-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
keeps only three indexes.siftDown
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.sortint[]