Skip to lesson

Build a heap yourself

Building a heap from scratch involves maintaining complete tree structure using sift-up, sift-down, and linear-time heapify.

Sift up on insertion

Sift up moves a new value up the heap, swapping it with its parent while it is smaller, until heap order holds again.

Sift up restores heap order after an insertion. The new value is added at the end of the array, which keeps the tree complete, then moves up while it is smaller than its parent.

Java
heap[size] = value;                  // 1. append at the end: the shape stays completeint i = size++;while (i > 0 && heap[i] < heap[(i - 1) / 2]) {   // 2. smaller than its parent?    int parent = (i - 1) / 2;    int tmp = heap[i];               // 3. swap child and parent    heap[i] = heap[parent];    heap[parent] = tmp;    i = parent;                      // 4. repeat from the parent's index}

Sift up after inserting 5

Step 1 of 4

1020153040
A min-heap of five values. We will insert the value 5.

Compare the new element at index i with its parent at (i - 1) / 2, swap if the child is smaller, and repeat until the parent is smaller or the element reaches index 0.

A complete tree of size n has height floor(log2 n), so sift-up needs at most O(log n) swaps.

Order of execution

Put sift up in order

Insert one value into a min-heap. Put the steps in the order the code runs them.

Sift down on removal

Removing the minimum element from a min-heap extracts the root item at index 0. To keep the tree complete, do not shift elements leftward in linear O(n) time. Instead, overwrite the root with the last element of the array, then decrement array size.

Sift down restores the min heap invariant

Step 1 of 4

30101520254050
Root holds value 30 after extracting minimum. We compare root with children at index 1 (value 10) and index 2 (value 15).

Example 1 · Custom MinHeap with Sift-Up and Sift-Down

Main.javaJava
public class Main {    static class MinHeap {        int[] heap;        int size;
        MinHeap(int capacity) {            heap = new int[capacity];            size = 0;        }
        void insert(int val) {            heap[size] = val;            siftUp(size);            size++;        }
        int extractMin() {            if (size == 0) throw new IllegalStateException("Heap is empty");            int min = heap[0];            heap[0] = heap[size - 1];            size--;            siftDown(0);            return min;        }
        void siftUp(int i) {            while (i > 0) {                int p = (i - 1) / 2;                if (heap[i] < heap[p]) {                    swap(i, p);                    i = p;                } else break;            }        }
        void siftDown(int i) {            while (2 * i + 1 < size) {                int smallest = i;                int left = 2 * i + 1;                int right = 2 * i + 2;                if (heap[left] < heap[smallest]) smallest = left;                if (right < size && heap[right] < heap[smallest]) smallest = right;                if (smallest != i) {                    swap(i, smallest);                    i = smallest;                } else break;            }        }
        void swap(int a, int b) {            int tmp = heap[a];            heap[a] = heap[b];            heap[b] = tmp;        }    }
    public static void main(String[] args) {        MinHeap h = new MinHeap(10);        h.insert(40);        h.insert(10);        h.insert(30);        h.insert(5);
        System.out.println("Extract: " + h.extractMin());        System.out.println("Extract: " + h.extractMin());        System.out.println("Extract: " + h.extractMin());    }}
Output
Extract: 5
Extract: 10
Extract: 30

What this code does

  • insert appends the element and bubbles it upward using siftUp.
  • extractMin swaps the root with the last item and restores invariant using siftDown.
  • Minimum values are returned in ascending order.

Now the tree structure remains complete, but the new root usually violates heap order. We restore order using the sift-down operation. Find the smaller of the node's left and right children. If that smallest child is smaller than the current node, swap them. Continue sifting downward until children satisfy heap order or a leaf is reached. Sift-down executes in at most O(log n) logarithmic steps.

Find the bug

Find the heap bug

Each snippet works with a min-heap stored in an array. Tap the wrong line.

Remove the minimum: move the last value to the root.

Round 1 of 3

Bottom-up heapify in linear O(n) time

Heapify turns an unsorted array into a heap by sifting down every internal node, from the last one back to the root, in O(n) time.

Building a heap by inserting n values one by one costs O(n log n). Bottom-up heapify builds the same heap faster, in O(n) time.

Example 2 · Brute force: insert one by one, O(n log n) time, O(1) extra space

Main.javaJava
public class Main {    static int swaps;
    static void siftUp(int[] h, int i) {        while (i > 0 && h[i] < h[(i - 1) / 2]) {            int p = (i - 1) / 2;            int t = h[i]; h[i] = h[p]; h[p] = t;            swaps++;            i = p;        }    }
    public static void main(String[] args) {        int[] data = {9, 8, 7, 6, 5, 4, 3, 2, 1};        int[] heap = new int[data.length];        for (int i = 0; i < data.length; i++) {            heap[i] = data[i];            siftUp(heap, i);          // every insert may climb log n levels        }        System.out.println(java.util.Arrays.toString(heap));        System.out.println("swaps: " + swaps);    }}
Output
[1, 2, 4, 3, 7, 8, 5, 9, 6]
swaps: 16

What this code does

  • Each of the 9 values is appended and then sifted up, so the loop makes one insertion per value.
  • The input is in descending order, the worst case: every new value climbs toward the root.
  • The swap counter shows the cost that bottom-up heapify avoids.

Example 3 · Optimal: bottom-up heapify, O(n) time, O(1) space

Main.javaJava
public class Main {    static void heapify(int[] arr) {        int n = arr.length;        for (int i = (n / 2) - 1; i >= 0; i--) {            siftDown(arr, n, i);        }    }
    static void siftDown(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 = {9, 8, 7, 6, 5, 4, 3, 2, 1};        heapify(arr);        System.out.println("Root after heapify: " + arr[0]);        System.out.print("Heap array: ");        for (int val : arr) System.out.print(val + " ");        System.out.println();    }}
Output
Root after heapify: 1
Heap array: 1 2 3 6 5 4 7 8 9 

What this code does

  • The loop begins at (n / 2) - 1, which is the last non-leaf node index.
  • Sift-down transforms each subtree bottom-up in O(n) total operations.
  • Smallest element 1 correctly surfaces at array root index 0.
  • It is faster because leaves cost nothing and most nodes sift down only one or two levels, instead of every value climbing to the root.

Example 4 · Building a Max-Heap In Place

Main.javaJava
public class Main {    static void buildMaxHeap(int[] arr) {        int n = arr.length;        for (int i = (n / 2) - 1; i >= 0; i--) {            siftDownMax(arr, n, i);        }    }
    static void siftDownMax(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[] nums = {12, 11, 13, 5, 6, 7};        buildMaxHeap(nums);        System.out.println("Max element at root: " + nums[0]);    }}
Output
Max element at root: 13

What this code does

  • Max-heap siftDown selects the largest child among left and right branches.
  • Running bottom-up across internal nodes guarantees the max-heap invariant.
  • The maximum array value 13 successfully lands at root index 0.

Nodes from index n / 2 to n - 1 are leaves, and a leaf is already a valid heap. So call sift-down on the internal nodes only, from index (n / 2) - 1 down to 0.

Most nodes sit near the bottom, where sift-down travels only a short distance. Adding up the work level by level gives O(n) in total.

Next step

Check your understanding

10 quick questions