Heaps
In questa pagina 5
A heap implements a priority queue (see Priority QueuesA priority queue is a collection of (key, value) entries where removal returns the entry with the smallest key (highest priority), and a list implementation makes either insertion or removal cost linear time.Priority Queues →) with min() in and insert(), removeMin() in , a good compromise between the two list implementations.
Complete binary tree
A binary tree (see Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees →) is an ordered tree where each internal node has at most two children, each non-root node is labelled left or right child, and the left child precedes the right one. A proper (full) binary tree has every internal node with exactly two children (proper is not perfect: perfect means all leaves at the same depth).
A complete binary tree of height satisfies:
- for every , , level contains nodes (the maximum possible);
- at level (the last), all internal nodes are to the left of any leaves, and each internal node has two children, except possibly the rightmost one, which may have only a left child.
Proposition. A complete binary tree with nodes has height .
Proof. Level has nodes for and the last level has between and nodes. So
Geometric series: and . Hence
Taking : . Since is an integer, it is the largest integer , i.e. . (Lower bound: all levels before the last are full and level has at least one node. Upper bound: a binary tree of height has at most as many nodes as the perfect tree of height .)
Heap
A min-heap (or simply heap) is a complete binary tree whose nodes store entries and satisfy the heap-order property: for a node with key and children ,
The key at each internal node is the keys of its children. A max-heap has . Keys are not necessarily distinct.
The Last node of a heap of height is the rightmost node at level .
Properties
Let be a min-heap with entries.
- The root contains an entry with the minimum key (one of the entries with minimum key).
- Keys along any path from the root to a leaf form a non-decreasing sequence.
- For every node and descendant : .
- If all keys are distinct, the entry with the maximum key is at one of the leaves.
- If all keys are distinct and is the entry with the -th smallest key, then is at depth .
Proof of 3. By definition of min-heap each parent has key its children's. Along any path from to a descendant : . Hence .
Proof of 5. Number the entries so that . Take the node of at depth = number of its ancestors (itself excluded). By heap order and distinct keys each of the ancestors has a key strictly smaller than , so at least entries have a smaller key. Exactly entries have a smaller key. Therefore , i.e. .
Two properties, two effects
- Complete binary tree: height , which bounds insertion and removal.
- Heap-order property:
min()in (root).
Example: sorted arrays are heaps
An array with keys in non-decreasing order always represents a min-heap. It is a complete binary tree (any array maps to one) and for with key and children with keys we have and , which is the heap-order property.
The converse is false: is a heap (2 5, 3 and 5 9, 7) but is not sorted (5 3 is false).
Example: traversals of a 7-entry heap
For a heap with 7 distinct keys, the preorder traversal can return the keys in increasing order: gives (a special case, not general). Inorder and postorder cannot, because the root (the minimum) is not visited first.
Array representation (level numbering)
A heap has a rigid complete structure, so it maps onto an array in level order (top to bottom, left to right), with no pointers and no empty cells:
- root ;
- children of , ;
- parent of .
The Last node is , so last . Navigation is index arithmetic.
Properties of the level numbering for a complete binary tree with nodes and height (provable by induction on the level):
- For , the nodes of level (left to right) go to positions with .
- The nodes of the last level go to positions (so Last ).
So the heap occupies exactly the first cells: any array can be seen as a complete binary tree with nodes (1:1 correspondence). Heaps are implicit data structures: relationships are encoded by positions.
For a generic (unbalanced or skewed) binary tree level numbering leaves many empty cells and the array size can grow exponentially in (e.g. nodes may need an array of 15 cells). Take-home: linked structures for generic trees, arrays for complete or nearly complete trees (compact, cache-efficient).
Priority queue methods on a heap
is a heap with entries in an array.
| Method | Description | Complexity |
|---|---|---|
size(), isEmpty() |
counter | |
min() |
return | |
insert(k, x) |
insert and restore heap order | |
removeMin() |
remove and restore heap order |
insert()
Idea: put the new entry right after Last, then restore heap order along the path from Last to the root (up-heap bubbling): while the child's key is smaller than its parent's, swap them.
Method insert(k, x)
e <- (k, x)
last <- last + 1
P[last] <- e
i <- last
// up-heap bubbling
while (i > 0) AND (P[floor((i-1)/2)].getKey() > P[i].getKey()) do
swap(P[i], P[floor((i-1)/2)]) // swap with parent
i <- floor((i-1)/2) // move to parent
return eOn overflow, first copy the entries into a larger array (e.g. double capacity): the resize is rare, so amortised per insertion.
Examples (heap of 12 keys: 4, 5, 9, 15, 16, 25, 14, 6, 20, 7, 12, 11).
insert(8, *): the heap order holds everywhere, no up-heap bubbling.insert(2, *): the path from the new node to the root passes through 20, 6, 4. Swap 2 with 20; 2 is still smaller than 6, swap; 2 is still smaller than 4, swap; 2 is now the root and bubbling stops.
Correctness. The shape (complete binary tree) is never violated: only a leaf is added after Last. Extended heap-order property: for ancestor of , key() key(). Loop invariant: at any time the only possible violation of heap order is between and its parent . At the start only the new entry can violate it with its parent. Each swap removes one local violation and moves it one level up. When the loop ends no parent-child pair violates the property, so by transitivity the extended heap-order property holds for the whole heap.
Complexity. Let be the height after insertion. Cost is proportional to the number of iterations, which is , so . Inserting a key smaller than all existing ones requires exactly iterations, so . Hence insert() is .
removeMin()
Idea: remove the root entry, move the Last entry to the root, restore heap order from the root down (down-heap bubbling): while the node is larger than its smaller child, swap with that child.
indexMinChild(P, i) returns the index of the child of with the smaller key ( or ) if is internal, null if it is a leaf.
Method removeMin()
minEntry <- P[0]
P[0] <- P[last]
last <- last - 1; i <- 0
j <- indexMinChild(P, i)
// down-heap bubbling
while (j != null) AND (P[i].getKey() > P[j].getKey()) do
swap(P[i], P[j]) // swap with the child of smaller key
i <- j
j <- indexMinChild(P, i)
return minEntryExample (13 keys: 4, 5, 9, 15, 16, 25, 14, 6, 20, 7, 12, 11, 13). removeMin() returns 4; the Last entry 13 moves to the root. Its smaller child is 5 (5 < 13): swap. Then the smaller child is 9 (< 13): swap. Then the smaller child is 12 (< 13): swap. 13 reaches a leaf and the heap order is restored.
Correctness. The shape is preserved (only the last leaf is removed). After moving to the root, heap order may be violated only between the new root and its children. Loop invariant: the only pairs that may violate heap order are with or (the smaller child). Each swap moves the larger key one level down, so a violation can only propagate along a path from the root to the leaves. At exit no parent-child pair violates the property, and by transitivity the extended heap order holds again.
Complexity. Let be the height after removal ( entries). Iterations , so . If has a key bigger than all the others it goes down to a leaf, exactly iterations, so . Hence removeMin() is .
Recap: priority queue implementations
| Structure | insert() |
min() |
removeMin() |
|---|---|---|---|
| Unsorted list | |||
| Sorted list | |||
| Heap (array) |
Exercises
Removing an arbitrary entry . Copy into position , remove the last leaf, then restore heap order at . The moved entry can violate heap order in both directions, so use up-heap or down-heap bubbling as needed.
Print all entries with key in time ( = number of such entries, plus 1 if none). Scanning the whole array is ; calling removeMin() until min().getKey() > k is (and modifies the heap). Neither has the required cost. The entries with key form a "cap" subtree over (by property 3 the ancestors of such an entry also have key ): visit only the nodes of with a preorder traversal, stopping at children with key .
Building a heap from entries
Goal: rearrange an array into a heap, in place. An algorithm is in-place if it uses only extra memory beyond the input (important for large datasets and for memory-limited devices).
Solution 0 (trivial). Move the entries into a temporary structure and call insert() times: extra space and time .
Solution 1: top-down, up-heap bubblings
for j <- 1 to n-1 do
i <- j
while (i > 0) AND (P[floor((i-1)/2)].getKey() > P[i].getKey()) do
swap(P[i], P[floor((i-1)/2)])
i <- floor((i-1)/2)Invariant at the end of iteration (): is a valid heap and is still in the original order. For the root alone is a heap. Iteration is an insert of into the heap , so the invariant is preserved. Same as insertions in an empty structure, but in place.
Complexity. A heap of nodes has height , and each insert is proportional to the height:
Upper bound: for every (the logarithm is increasing), so . Starting the sum at instead of changes nothing since . Lower bound: take only the last half of the terms, : each is and there are about of them, so
The bad instance is an array initially sorted in decreasing order of keys (every insertion bubbles up to the root). Hence for any constant base and the top-down construction costs : in place, but not faster than Solution 0.
Solution 2: bottom-up, down-heap bubblings
Start from the parent of Last, (rightmost internal node of the penultimate level), and go up to the root. The leaves ( nodes) are already one-node heaps.
for j <- floor((n-2)/2) downto 0 do
// down-heap bubbling starting from P[j]
i <- j
k <- indexMinChild(P, i)
while (k != null) AND (P[i].getKey() > P[k].getKey()) do
swap(P[i], P[k])
i <- k
k <- indexMinChild(P, i)Since , the loop runs times, once per internal node.
Invariant at the end of iteration : the prefix is unchanged and the suffix is a forest of heaps. Each iteration performs a down-heap bubbling from , making the subtree rooted at a valid heap (its two subtrees are already heaps).
Example. , , so goes from 5 to 0. Applying the algorithm:
| swap performed | array after the iteration | |
|---|---|---|
| 5 | none (13 15) | |
| 4 | 11 with 1 | |
| 3 | none (9 30, 18) | same |
| 2 | 27 with 5 | |
| 1 | 10 with 1 | |
| 0 | 2 with 1 |
Complexity. Let . A node at level can move down to the leaves at most, so its down-heap costs ; level has nodes. The loop overhead is ( iterations with constant work each). So
Claim 1. .
Step 1: for all , by induction. Base: : ; : . Step ():
because .
Step 2: by the geometric sum and dropping the non-negative term ,
Claim 2. .
with , independent of , Claim 1, and since .
Hence the bottom-up construction is , and since it must read every entry, .
Top-down vs bottom-up
| Top-down | Bottom-up | |
|---|---|---|
| Work per level | operations of cost | operations of cost |
| Trend | the deeper the level, the costlier the up-heap | the deeper the level, the cheaper the down-heap |
| Total |
Both are in place.
Versione ripasso
- Complete binary tree: levels full ( nodes), last level filled left to right. nodes give (from ). See Priority QueuesA priority queue is a collection of (key, value) entries where removal returns the entry with the smallest key (highest priority), and a list implementation makes either insertion or removal cost linear time.Priority Queues →.
- Min-heap = complete binary tree + heap order (parent key children keys). Max-heap: . Last = rightmost node of the last level.
- Properties: root has the min; keys along a root-leaf path are non-decreasing; ancestor descendant (chain of parent child); if keys are distinct, the max is at a leaf and has depth (its ancestors are distinct smaller keys, but only exist).
- Non-decreasing arrays are heaps; the converse is false ().
- Level numbering: root ; children ; parent ; Last . Level at . Implicit and compact for complete trees; generic skewed trees waste space (exponential).
- insert: add after Last, up-heap bubbling (swap with parent while parent key child key). Invariant: only violation is between and its parent. .
- removeMin: save , move to the root, down-heap bubbling (swap with the smaller child while ). Invariant: only violation is between and its smaller child. .
min();size,isEmpty. Worst cases: insert of a new minimum, removeMin when the moved entry is the largest.- Remove arbitrary : put there; may need up- or down-heap bubbling.
- Build a heap in place:
- top-down, up-heap bubblings: (upper bound ; lower bound last half of the terms);
- bottom-up, down to 0 ( iterations, forest-of-heaps invariant): , so .
- Typical mistakes: bubbling with the larger child in removeMin; using instead of for Last; thinking bottom-up costs tightly.