7.1Heap with an Array
A heap in an array: indexes and the heap rule
A heap is always complete, so it fits in an array with no gaps. The index formulas from binary tree in an array apply unchanged. In this lesson we set up the heap's structure, write peek, which looks at the minimum, and check whether an array really is a heap.
- How a heap sits in an array and what the
countfield does - Why looking at the minimum takes O(1)
- How to check the heap property by comparing each node with its parent
1Idea
A heap has the same structure as a tree in an array: an array and a count that says how many cells are used. The used cells run from 0 to count - 1, and the root is in items[0]. The node at index i has its children at 2*i+1 and 2*i+2 and its parent at (i-1)/2. This lesson needs only the parent formula; the child formulas are used in the sift down lesson.
In a min-heap the smallest value is at the root, so peek simply reads items[0]. If the heap is empty there is nothing to read: C returns false, Java and Python throw an error. You saw the same behaviour in the priority queue lessons.
To check whether an array is a heap you look at every parent and its children. Doing it the other way round is shorter: for every node except the root, that is for i from 1 to count - 1, check that its parent is not larger than it. If even one larger parent is found, the array is not a heap. The shape rule needs no separate check: the array has no gaps, so the tree is already complete.
An empty heap and a heap with one element both follow the rule: there is no parent-child pair to check, the loop never runs, and the result is true. Equal values do not break the rule either, because the rule says "smaller than or equal".
2Step by step
The array in the drawing is 10, 20, 15, 40, 12, 30, 25. We run the code on it step by step. The same array is drawn as a tree on top.
- Start.
countis 7. The root is 10, which looks like the smallest value, but we do not know yet whether this array is a heap. i = 1. Its parent is(1-1)/2 = 0: 10 is compared with 20. 10 is not larger than 20; the rule holds.i = 2. The parent is 0 again: 10 and 15. The rule holds.i = 3. Its parent is(3-1)/2 = 1: 20 and 40. The rule holds.i = 4. Its parent is(4-1)/2 = 1: 20 and 12. The parent is larger than its child: the rule is broken. The function returnsfalse; the remaining nodes are not checked.
#define CAPACITY 15 struct Heap { int items[CAPACITY]; int count; // number of elements in the heap}; void create(struct Heap* h) { h->count = 0;} int parent(int i) { return (i - 1) / 2;} bool peek(struct Heap* h, int* value) { if (h->count == 0) { return false; // heap is empty } *value = h->items[0]; // the minimum is always at the root return true;} bool isHeap(struct Heap* h) { for (int i = 1; i < h->count; i++) { if (h->items[parent(i)] > h->items[i]) { return false; // a child is smaller than its parent } } return true;}class ArrayHeap { int[] items; int count = 0; // number of elements in the heap ArrayHeap(int capacity) { items = new int[capacity]; } int parent(int i) { return (i - 1) / 2; } int peek() { if (count == 0) { throw new IllegalStateException("heap is empty"); } return items[0]; // the minimum is always at the root } boolean isHeap() { for (int i = 1; i < count; i++) { if (items[parent(i)] > items[i]) { return false; // a child is smaller than its parent } } return true; }}class ArrayHeap: def __init__(self, capacity): self.items = [None] * capacity self.count = 0 # number of elements in the heap def parent(self, i): return (i - 1) // 2 def peek(self): if self.count == 0: raise IndexError("heap is empty") return self.items[0] # the minimum is always at the root def is_heap(self): for i in range(1, self.count): if self.items[self.parent(i)] > self.items[i]: return False # a child is smaller than its parent return TrueThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Every node except the root is compared with its parent once: n - 1 comparisons in the worst case. peek is a single read, O(1).
Only the loop variable is used.
The real heap operations never run this check. Insertion and removal keep the rule only along the path that changes. isHeap is useful when writing tests and for the exam question "is this array a heap?"
4Common mistake
A common mistake is comparing siblings:
if (h->items[2 * i + 1] > h->items[2 * i + 2]) { return false; // wrong: left and right have no order}The heap property holds only between a parent and a child. The left child may be larger than the right one; the array 10, 20, 15 is a heap. Expecting left and right to be in order means mixing up a heap with a binary search tree.
5Try it
Which array is a min-heap?
The answer is A. In the first array every node is larger than or equal to its parent: 5 and 4 have parent 3, 9 and 6 have parent 5, 8 has parent 4. In the second, 2 is smaller than its parent 5. In the third, 3 is smaller than its parent 5.
Show the answer
The answer is A. In the first array every node is larger than or equal to its parent: 5 and 4 have parent 3, 9 and 6 have parent 5, 8 has parent 4. In the second, 2 is smaller than its parent 5. In the third, 3 is smaller than its parent 5.
When the heap is not empty, which cell does peek read?
The answer is B. In a min-heap the smallest value is at the root, and the root is always at index 0. items[count - 1] is the last place filled; its value could be anything.
Show the answer
The answer is B. In a min-heap the smallest value is at the root, and the root is always at index 0. items[count - 1] is the last place filled; its value could be anything.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.