7.1Heap with an Array
Insert: sift up
Inserting a value into a heap has to keep both rules. The shape rule is easy: as in a tree in an array, the value is written to the next free place, items[count]. But if the new value is small, the heap property breaks. The way to fix it is to move the value up by swapping it with its parent: sift up.
- Why the new value is first written at the end
- When sift up stops
- Why an insertion makes at most as many swaps as the height of the tree
1Idea
Insertion has two steps. First the value is written to items[count] and count is increased; the tree stays complete. Then the new value is checked against its parent. If the parent is larger than the new value, the rule is broken: the two swap places. The new value is now one level higher, and the same check is repeated with its new parent.
The loop stops in one of two cases: the value reaches the root (i == 0), or its parent is no longer larger than it. In the second case the rule holds everywhere, because the only values that changed are the ones on this path, and sift up has put them in order.
Why is checking this path enough? The parent that moves down in a swap was already smaller than the other child of its new position, because the heap property held before the insertion. So the value that moves down does not break the rule in its new place either.
On an equal value the loop stops: the condition is written with >, not >=. Swapping equal values does not change the rule; it only does useless work.
2Step by step
The heap in the drawing is 10, 20, 15, 40, 50, 30. We insert 5 into it. The tree is on top and the array below; i shows the index of the new value.
- Start. The heap holds 6 values and
countis 6. The smallest value, 10, is at the root. insert(5). First the full check: there are 6 elements and the capacity is 15. There is room.- 5 is written to the next free place,
items[6], andcountbecomes 7. Its parent is(6-1)/2 = 2: 15. It is now 15's right child. Sift up starts withi = 6. - The parent 15 is larger than the new value 5: the rule is broken.
- 5 and 15 swap places. 5 is now in cell 2, and
ibecomes 2. - The new parent is
(2-1)/2 = 0: 10. 10 is larger than 5 too. - 5 and 10 swap places. 5 has reached the root, and
ibecomes 0. i == 0: the loop stops. The new smallest value, 5, is at the root. The path that changed is 15, 10, 5; the rest of the tree was not touched.
#define CAPACITY 15 struct Heap { int items[CAPACITY]; int count;}; int parent(int i) { return (i - 1) / 2; } 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 siftUp(struct Heap* h, int i) { while (i > 0 && h->items[parent(i)] > h->items[i]) { swap(h, i, parent(i)); // the smaller one moves up i = parent(i); }} bool insert(struct Heap* h, int value) { if (h->count == CAPACITY) { return false; // heap is full } h->items[h->count] = value; // the next free place h->count++; siftUp(h, h->count - 1); return true;}class ArrayHeap { int[] items; int count = 0; ArrayHeap(int capacity) { items = new int[capacity]; } int parent(int i) { return (i - 1) / 2; } void swap(int i, int j) { int temp = items[i]; items[i] = items[j]; items[j] = temp; } void siftUp(int i) { while (i > 0 && items[parent(i)] > items[i]) { swap(i, parent(i)); // the smaller one moves up i = parent(i); } } void insert(int value) { if (count == items.length) { throw new IllegalStateException("heap is full"); } items[count] = value; // the next free place count++; siftUp(count - 1); }}class ArrayHeap: def __init__(self, capacity): self.items = [None] * capacity self.count = 0 def parent(self, i): return (i - 1) // 2 def swap(self, i, j): self.items[i], self.items[j] = self.items[j], self.items[i] def sift_up(self, i): while i > 0 and self.items[self.parent(i)] > self.items[i]: self.swap(i, self.parent(i)) # the smaller one moves up i = self.parent(i) def insert(self, value): if self.count == len(self.items): raise IndexError("heap is full") self.items[self.count] = value # the next free place self.count += 1 self.sift_up(self.count - 1)The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
The new value climbs from a leaf toward the root, one level per swap. A complete tree has a height of log₂ n, so at most log₂ n swaps are made. In the best case (the new value is larger than its parent) there is no swap at all, O(1).
A few variables are enough; the loop is not recursive.
Inserting into a priority queue built on a sorted array took O(n), because elements were shifted to make room. In a heap the value only travels along its own path. With a million elements that means at most 20 swaps.
4Common mistake
A common mistake is starting sift up before count is increased, or with the wrong index:
h->count++;h->items[h->count] = value; // wrong: one cell stays emptysiftUp(h, h->count); // wrong indexThe value must be written to items[count], and only then is count increased. After the increase, the new value's index is count - 1, and sift up starts from there. In the wrong order the heap gets a gap and sift up moves the wrong value.
5Try it
What does the array become when 4 is inserted into the heap 3, 8, 5, 10, 9, 7?
The answer is A. 4 is written to cell 6. Its parent is at (6-1)/2 = 2, which holds 5; 5 > 4, so they swap. The new parent is 3 at position 0; 3 < 4, so the loop stops.
Show the answer
The answer is A. 4 is written to cell 6. Its parent is at (6-1)/2 = 2, which holds 5; 5 > 4, so they swap. The new parent is 3 at position 0; 3 < 4, so the loop stops.
At most how many swaps are made when a value is inserted into a heap of 31 elements?
The answer is B. A complete tree with 32 nodes has a height of 5 (1 + 2 + 4 + 8 + 16 = 31 nodes fit in a height of four edges, and node 32 opens a fifth). The new value starts at the bottom and makes at most 5 swaps up to the root.
Show the answer
The answer is B. A complete tree with 32 nodes has a height of 5 (1 + 2 + 4 + 8 + 16 = 31 nodes fit in a height of four edges, and node 32 opens a fifth). The new value starts at the bottom and makes at most 5 swaps up to the root.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.