algoritmauzmanı
Sign in
TREN
7.1Heap with an Array
Lesson 7.1.4

Building a heap from an array (heapify)

If you have n values, inserting them one by one takes O(n log n). There is a faster way: put the values into the array as they are, then fix the tree from the bottom up. This is called and takes only O(n). It is also the first step of heap sort.

What you will learn
  • Why building a heap starts at the last inner node
  • Why sifting down a node turns its whole subtree into a heap
  • Why heapify takes O(n) rather than O(n log n)
7 minTime O(n)Memory O(1)C · Java · Python

1Idea

The values are first copied into the array in their original order. The array has no gaps, so the tree is complete; only the may be broken. To establish it, every inner node is sifted down, but the order matters: you start with the lower nodes and work up to the root.

Why from the bottom? Sift down assumes that the two subtrees below a node are already heaps. Leaves are heaps on their own. When the last inner node is sifted down, its subtree becomes a heap. Then you move to the inner node before it; the subtrees of its children are now heaps. By the time you reach the root, the whole tree is a heap.

There is no need to touch the leaves; they have no children, so sift down does nothing on them. In an array of n elements the last inner node is the parent of the last element: (n-1-1)/2, that is n/2 - 1. The loop counts backwards from this index to 0.

Inserting the values one by one also gives a correct heap, but the resulting array may differ from heapify's. An exam may ask "build by inserting" and "build with heapify" as separate questions; check which one is asked.

2Step by step

The array in the drawing is 50, 30, 40, 10, 20, 15. It is not a heap. With 6 elements the last inner node is at index 6/2 - 1 = 2; the loop sifts down indexes 2, 1 and 0 in that order.

items0123455050303040401010202015156countismallest
  1. The values are copied and count is 6. The tree is complete but not a heap: the largest value, 50, is at the root.
  2. i = 2: 40 is sifted down. Its only child is 15; 15 < 40.
  3. 40 and 15 swap. 40 has reached a leaf; the subtree of node 2 is now a heap.
  4. i = 1: 30 is sifted down. Its children are 10 and 20; the smaller is 10.
  5. 30 and 10 swap. 30 has reached a leaf; the subtree of node 1 is a heap too.
  6. i = 0: 50 is sifted down. Its children are 10 and 15; the smaller is 10.
  7. 50 and 10 swap. 50 has not stopped yet: it has children in its new place too.
  8. 50's new children are 30 and 20; the smaller is 20, and 20 < 50.
  9. 50 and 20 swap. 50 has reached a leaf.
  10. The loop is over: the array is 10, 20, 15, 30, 50, 40, and it is a heap. Four swaps were enough.

#define CAPACITY 15 struct Heap {    int items[CAPACITY];    int count;}; void swap(struct Heap* h, int i, int j) {    int temp = h->items[i];    h->items[i] = h->items[j];    h->items[j] = temp;} void siftDown(struct Heap* h, int i) {    while (true) {        int smallest = i;        int left = 2 * i + 1, right = 2 * i + 2;        if (left < h->count && h->items[left] < h->items[smallest]) smallest = left;        if (right < h->count && h->items[right] < h->items[smallest]) smallest = right;        if (smallest == i) return;        swap(h, i, smallest);        i = smallest;    }} bool buildHeap(struct Heap* h, int arr[], int n) {    if (n > CAPACITY) {        return false;  // does not fit    }    for (int k = 0; k < n; k++) {        h->items[k] = arr[k];  // copy as it is first    }    h->count = n;    for (int i = n / 2 - 1; i >= 0; i--) {        siftDown(h, i);  // from the last inner node up to the root    }    return true;}
class ArrayHeap {    int[] items;    int count = 0;     ArrayHeap(int capacity) {        items = new int[capacity];    }     void swap(int i, int j) {        int temp = items[i];        items[i] = items[j];        items[j] = temp;    }     void siftDown(int i) {        while (true) {            int smallest = i;            int left = 2 * i + 1, right = 2 * i + 2;            if (left < count && items[left] < items[smallest]) smallest = left;            if (right < count && items[right] < items[smallest]) smallest = right;            if (smallest == i) return;            swap(i, smallest);            i = smallest;        }    }     void buildHeap(int[] arr) {        if (arr.length > items.length) {            throw new IllegalStateException("heap is full");        }        for (int k = 0; k < arr.length; k++) {            items[k] = arr[k];  // copy as it is first        }        count = arr.length;        for (int i = count / 2 - 1; i >= 0; i--) {            siftDown(i);  // from the last inner node up to the root        }    }}
class ArrayHeap:    def __init__(self, capacity):        self.items = [None] * capacity        self.count = 0     def swap(self, i, j):        self.items[i], self.items[j] = self.items[j], self.items[i]     def sift_down(self, i):        while True:            smallest = i            left, right = 2 * i + 1, 2 * i + 2            if left < self.count and self.items[left] < self.items[smallest]:                smallest = left            if right < self.count and self.items[right] < self.items[smallest]:                smallest = right            if smallest == i:                return            self.swap(i, smallest)            i = smallest     def build_heap(self, arr):        if len(arr) > len(self.items):            raise IndexError("heap is full")        for k in range(len(arr)):            self.items[k] = arr[k]  # copy as it is first        self.count = len(arr)        for i in range(self.count // 2 - 1, -1, -1):            self.sift_down(i)  # from the last inner node up to the root

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

Sifting a node down takes at most its own height. Half of the nodes are leaves and do no work; a quarter go down at most 1 level, an eighth at most 2. The total n/4 · 1 + n/8 · 2 + n/16 · 3 + ... never exceeds n: O(n).

Memory
O(1)

The values are copied into the heap's own array; sift down needs a few variables.

Inserting the values one by one takes O(n log n), because each new value may climb all the way to the root and half of the values sit on the lowest level. In heapify the nodes that can travel a long way, the ones near the root, are few.

4Common mistake

A common mistake is starting the loop at 0:

for (int i = 0; i <= n / 2 - 1; i++) {    siftDown(h, i);   // wrong: top to bottom}

When the root is sifted down first, the subtrees below it are not heaps yet, and the root may stop in the wrong place. With the array 3, 9, 8, 1, the 3 stays put, then 9 and 1 swap, and 1 ends up below the 3 at the root. The loop must run from the end towards the start.

5Try it

What is the result of applying heapify to the array 9, 4, 7, 1, 2, 6, 3?

Show the answer

The answer is A. The last inner node is 2: 7's children are 6 and 3, it swaps with 3: 9, 4, 3, 1, 2, 6, 7. Index 1: 4's children are 1 and 2, it swaps with 1: 9, 1, 3, 4, 2, 6, 7. The root: 9's children are 1 and 3, it swaps with 1; 9's new children are 4 and 2, it swaps with 2: 1, 2, 3, 4, 9, 6, 7.

In an array of 100 elements, at which index does the heapify loop start?

Show the answer

The answer is C. The last element is at index 99; its parent is (99-1)/2 = 49. Index 50 and beyond are leaves, where sift down does no work.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.