Skip to lesson

Heap sort is an in-place sorting algorithm that uses a heap structure to sort arrays without extra memory.

Building a max heap in place

Heap sort is an in-place sort that builds a max-heap and then repeatedly swaps the root, the largest value, to the end of the array.

Heap sort sorts an array by building a max-heap and then repeatedly moving the largest value to the back. Phase one turns the input array into a max-heap in place.

Java
int n = arr.length;for (int i = n / 2 - 1; i >= 0; i--) {   // last internal node back to the root    siftDown(arr, n, i);                  // push arr[i] below its larger children}// arr is now a max-heap: arr[0] holds the largest value

Run bottom-up heapify from index (n / 2) - 1 down to 0. This takes O(n) time, and the largest value ends up at index 0.

Merge sort needs O(n) extra memory and quicksort can degrade to O(n^2) time. Heap sort guarantees O(n log n) time with O(1) extra memory.

Repeatedly moving the max to the end

In phase two, we extract the maximum element repeatedly and place it into its final sorted position. Swap root index 0 with the boundary index i, beginning at index n - 1. The largest element is now permanently placed at index i.

Moving the largest values to the back

Step 1 of 5

968257
A max-heap of six values. The largest, 9, is at the root. Swap it with the last item, 7, to put 9 in its final place.

Example 1 · Brute force: selection sort, O(n^2) time, O(1) space

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int[] a = {29, 10, 14, 37, 13};        for (int i = 0; i < a.length - 1; i++) {            int min = i;            for (int j = i + 1; j < a.length; j++) {   // scans the whole unsorted part                if (a[j] < a[min]) min = j;            }            int t = a[i]; a[i] = a[min]; a[min] = t;        }        System.out.println(Arrays.toString(a));    }}
Output
[10, 13, 14, 29, 37]

What this code does

  • For every position the inner loop scans all remaining values to find the smallest, so about n * n / 2 comparisons run.
  • The array is sorted in place, so extra space is O(1), the same as heap sort.
  • Heap sort replaces that scan with a heap, which finds the next value in O(log n).

Example 2 · Optimal: heap sort, O(n log n) time, O(1) space

Main.javaJava
public class Main {    static void heapSort(int[] arr) {        int n = arr.length;        // Phase 1: Build max heap        for (int i = (n / 2) - 1; i >= 0; i--) {            siftDown(arr, n, i);        }        // Phase 2: Extract max repeatedly        for (int i = n - 1; i > 0; i--) {            int tmp = arr[0];            arr[0] = arr[i];            arr[i] = tmp;            siftDown(arr, i, 0);        }    }
    static void siftDown(int[] arr, int n, int i) {        while (2 * i + 1 < n) {            int largest = i;            int left = 2 * i + 1;            int right = 2 * i + 2;            if (arr[left] > arr[largest]) largest = left;            if (right < n && arr[right] > arr[largest]) largest = right;            if (largest != i) {                int tmp = arr[i];                arr[i] = arr[largest];                arr[largest] = tmp;                i = largest;            } else break;        }    }
    public static void main(String[] args) {        int[] arr = {12, 11, 13, 5, 6, 7};        heapSort(arr);        for (int v : arr) System.out.print(v + " ");        System.out.println();    }}
Output
5 6 7 11 12 13 

What this code does

  • Phase 1 constructs the initial max-heap in linear time.
  • Phase 2 moves the largest element to the back and shrinks active heap bounds.
  • Resulting array is sorted in ascending order.
  • It is faster because the heap keeps the largest value at the root, so each extraction costs O(log n) instead of a scan of O(n).

Example 3 · Descending Order Heap Sort Using Min-Heap

Main.javaJava
public class Main {    static void heapSortDescending(int[] arr) {        int n = arr.length;        // Phase 1: Build min heap        for (int i = (n / 2) - 1; i >= 0; i--) {            siftDownMin(arr, n, i);        }        // Phase 2: Move min to end repeatedly        for (int i = n - 1; i > 0; i--) {            int tmp = arr[0];            arr[0] = arr[i];            arr[i] = tmp;            siftDownMin(arr, i, 0);        }    }
    static void siftDownMin(int[] arr, int n, int i) {        while (2 * i + 1 < n) {            int smallest = i;            int left = 2 * i + 1;            int right = 2 * i + 2;            if (arr[left] < arr[smallest]) smallest = left;            if (right < n && arr[right] < arr[smallest]) smallest = right;            if (smallest != i) {                int tmp = arr[i];                arr[i] = arr[smallest];                arr[smallest] = tmp;                i = smallest;            } else break;        }    }
    public static void main(String[] args) {        int[] arr = {4, 10, 3, 5, 1};        heapSortDescending(arr);        for (int v : arr) System.out.print(v + " ");        System.out.println();    }}
Output
10 5 4 3 1 

What this code does

  • Building a min-heap allows sorting an array in descending order in place.
  • The minimum element is repeatedly swapped to the end boundary.
  • Output shows strictly descending sorted order.

Example 4 · Tracing Array State After Each Extraction

Main.javaJava
import java.util.Arrays;
public class Main {    static void siftDown(int[] arr, int n, int i) {        while (2 * i + 1 < n) {            int largest = i;            int left = 2 * i + 1;            int right = 2 * i + 2;            if (arr[left] > arr[largest]) largest = left;            if (right < n && arr[right] > arr[largest]) largest = right;            if (largest != i) {                int tmp = arr[i]; arr[i] = arr[largest]; arr[largest] = tmp;                i = largest;            } else break;        }    }
    public static void main(String[] args) {        int[] arr = {4, 10, 3, 5, 1};        int n = arr.length;        for (int i = (n / 2) - 1; i >= 0; i--) siftDown(arr, n, i);        System.out.println("Max-heap: " + Arrays.toString(arr));
        for (int i = n - 1; i > 0; i--) {            int tmp = arr[0]; arr[0] = arr[i]; arr[i] = tmp;            siftDown(arr, i, 0);            System.out.println("Step i=" + i + ": " + Arrays.toString(arr));        }    }}
Output
Max-heap: [10, 5, 3, 4, 1]
Step i=4: [5, 4, 3, 1, 10]
Step i=3: [4, 1, 3, 5, 10]
Step i=2: [3, 1, 4, 5, 10]
Step i=1: [1, 3, 4, 5, 10]

What this code does

  • Max-heap initial state places 10 at the root.
  • Each step swaps the current maximum to the end boundary.
  • The prefix shrinks while the sorted suffix grows.

Next, shrink the effective heap size to i, excluding all elements that are already sorted. The new value at index 0 almost certainly violates the max-heap property. Restore the max-heap invariant by calling sift-down on index 0 within the reduced range of size i. Repeat this swap and sift-down cycle for every boundary index from n - 1 down to 1. Each extraction costs O(log n) time. After n - 1 iterations, the array is sorted in ascending order.

Complexity, stability, and comparison with merge sort

Heap sort runs in O(n log n) time across best, average, and worst cases. Phase one takes O(n) time. Phase two takes (n - 1) * O(log n), giving O(n log n) overall. Because all swaps occur in place, the auxiliary space complexity is strictly O(1).

However, heap sort is not a stable sort. Long-distance swaps between index 0 and boundary index i can alter the relative order of duplicate keys.

Compared with merge sort, heap sort requires zero additional memory arrays. However, merge sort provides stability and superior CPU cache locality due to sequential memory access. Heap sort accesses memory across index powers of two, leading to higher CPU cache miss rates.

Next step

Check your understanding

10 quick questions