Salta al contenuto
Note per Studenti Heaps Report

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 Θ(1)\Theta(1) and insert(), removeMin() in Θ(log⁡n)\Theta(\log n), 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 TT of height hh satisfies:

  • for every ii, 0≤i≤h−10 \le i \le h-1, level ii contains 2i2^i nodes (the maximum possible);
  • at level hh (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 nn nodes has height h=⌊log⁡2n⌋h = \lfloor \log_2 n \rfloor.

Proof. Level ii has 2i2^i nodes for i≤h−1i \le h-1 and the last level has between 11 and 2h2^h nodes. So

∑i=0h−12i+1≤n≤∑i=0h2i.\sum_{i=0}^{h-1} 2^i + 1 \le n \le \sum_{i=0}^{h} 2^i .

Geometric series: ∑i=0h−12i+1=2h−1+1=2h\sum_{i=0}^{h-1} 2^i + 1 = 2^h - 1 + 1 = 2^h and ∑i=0h2i=2h+1−1\sum_{i=0}^{h} 2^i = 2^{h+1} - 1. Hence

2h≤n≤2h+1−1<2h+1.2^h \le n \le 2^{h+1} - 1 < 2^{h+1}.

Taking log⁡2\log_2: h≤log⁡2n<h+1h \le \log_2 n < h+1. Since hh is an integer, it is the largest integer ≤log⁡2n\le \log_2 n, i.e. h=⌊log⁡2n⌋h = \lfloor \log_2 n \rfloor. (Lower bound: all levels before the last are full and level hh has at least one node. Upper bound: a binary tree of height hh has at most as many nodes as the perfect tree of height hh.) □\square

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 k1k_1 and children k2,k3k_2, k_3,

k1≤min⁡{k2,k3}.k_1 \le \min\{k_2, k_3\}.

The key at each internal node is ≤\le the keys of its children. A max-heap has k1≥max⁡{k2,k3}k_1 \ge \max\{k_2, k_3\}. Keys are not necessarily distinct.

The Last node of a heap of height hh is the rightmost node at level hh.

Properties

Let PP be a min-heap with nn entries.

  1. The root contains an entry with the minimum key (one of the entries with minimum key).
  2. Keys along any path from the root to a leaf form a non-decreasing sequence.
  3. For every node vv and descendant uu: eu.getKey()≥ev.getKey()e_u.\text{getKey}() \ge e_v.\text{getKey}().
  4. If all keys are distinct, the entry with the maximum key is at one of the leaves.
  5. If all keys are distinct and eie_i is the entry with the ii-th smallest key, then eie_i is at depth d<id < i.

Proof of 3. By definition of min-heap each parent has key ≤\le its children's. Along any path from vv to a descendant uu: Kv≤K1≤K2≤⋯≤KuK_v \le K_1 \le K_2 \le \dots \le K_u. Hence eu.getKey()≥ev.getKey()e_u.\text{getKey}() \ge e_v.\text{getKey}(). □\square

Proof of 5. Number the entries so that Ke1<Ke2<⋯<KenK_{e_1} < K_{e_2} < \dots < K_{e_n}. Take the node of eie_i at depth dd = number of its ancestors (itself excluded). By heap order and distinct keys each of the dd ancestors has a key strictly smaller than KeiK_{e_i}, so at least dd entries have a smaller key. Exactly i−1i-1 entries have a smaller key. Therefore d≤i−1d \le i-1, i.e. d<id < i. □\square

Two properties, two effects

  • Complete binary tree: height Θ(log⁡n)\Theta(\log n), which bounds insertion and removal.
  • Heap-order property: min() in O(1)O(1) (root).

Example: sorted arrays are heaps

An array P[0..n−1]P[0..n-1] with keys in non-decreasing order always represents a min-heap. It is a complete binary tree (any array maps to one) and for P[i]P[i] with key kk and children P[2i+1],P[2i+2]P[2i+1], P[2i+2] with keys k′,k′′k', k'' we have k≤k′k \le k' and k≤k′′k \le k'', which is the heap-order property.

The converse is false: P=[2,5,3,9,7]P = [2, 5, 3, 9, 7] is a heap (2 ≤\le 5, 3 and 5 ≤\le 9, 7) but is not sorted (5 ≤\le 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: P=[1,2,5,3,4,6,7]P = [1, 2, 5, 3, 4, 6, 7] gives 1,2,3,4,5,6,71, 2, 3, 4, 5, 6, 7 (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 P[0],P[1],…P[0], P[1], \dots in level order (top to bottom, left to right), with no pointers and no empty cells:

  • root →P[0]\to P[0];
  • children of P[i]P[i] →P[2i+1]\to P[2i+1], P[2i+2]P[2i+2];
  • parent of P[i]P[i] →P[⌊(i−1)/2⌋]\to P\left[\lfloor (i-1)/2 \rfloor\right].

The Last node is P[n−1]P[n-1], so last =n−1= n-1. Navigation is index arithmetic.

Properties of the level numbering for a complete binary tree with n≥1n \ge 1 nodes and height hh (provable by induction on the level):

  1. For 0≤i<h0 \le i < h, the 2i2^i nodes of level ii (left to right) go to positions P[j]P[j] with 2i−1≤j≤2i+1−22^i - 1 \le j \le 2^{i+1} - 2.
  2. The nodes of the last level hh go to positions 2h−1≤j≤n−12^h - 1 \le j \le n-1 (so Last =n−1= n-1).

So the heap occupies exactly the first nn cells: any array P[0..n−1]P[0..n-1] can be seen as a complete binary tree with nn 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 nn (e.g. n=7n = 7 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

PP is a heap with nn entries in an array.

Method Description Complexity
size(), isEmpty() counter nn Θ(1)\Theta(1)
min() return P[0]P[0] Θ(1)\Theta(1)
insert(k, x) insert and restore heap order Θ(log⁡n)\Theta(\log n)
removeMin() remove P[0]P[0] and restore heap order Θ(log⁡n)\Theta(\log n)

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 e

On overflow, first copy the entries into a larger array (e.g. double capacity): the O(n)O(n) resize is rare, so amortised O(1)O(1) 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 uu of vv, key(uu) ≤\le key(vv). Loop invariant: at any time the only possible violation of heap order is between P[i]P[i] and its parent P[⌊(i−1)/2⌋]P[\lfloor (i-1)/2 \rfloor]. 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 h=⌊log⁡2(n+1)⌋h = \lfloor \log_2(n+1) \rfloor be the height after insertion. Cost is proportional to the number of iterations, which is ≤h\le h, so O(h)O(h). Inserting a key smaller than all existing ones requires exactly hh iterations, so Ω(h)\Omega(h). Hence insert() is Θ(log⁡n)\Theta(\log n).

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 P[i]P[i] with the smaller key (2i+12i+1 or 2i+22i+2) if P[i]P[i] 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 minEntry

Example (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 P[last]P[last] 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 (P[i],P[j])(P[i], P[j]) with j=2i+1j = 2i+1 or 2i+22i+2 (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 h=⌊log⁡2(n−1)⌋h = \lfloor \log_2(n-1) \rfloor be the height after removal (n−1n-1 entries). Iterations ≤h\le h, so O(h)O(h). If P[last]P[last] has a key bigger than all the others it goes down to a leaf, exactly hh iterations, so Ω(h)\Omega(h). Hence removeMin() is Θ(log⁡n)\Theta(\log n).

Recap: priority queue implementations

Structure insert() min() removeMin()
Unsorted list Θ(1)\Theta(1) Θ(n)\Theta(n) Θ(n)\Theta(n)
Sorted list Θ(n)\Theta(n) Θ(1)\Theta(1) Θ(1)\Theta(1)
Heap (array) Θ(log⁡n)\Theta(\log n) Θ(1)\Theta(1) Θ(log⁡n)\Theta(\log n)

Exercises

Removing an arbitrary entry P[j]P[j]. Copy P[last]P[last] into position jj, remove the last leaf, then restore heap order at P[j]P[j]. 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 ≤k\le k in time Θ(nk)\Theta(n_k) (nkn_k = number of such entries, plus 1 if none). Scanning the whole array is Θ(n)\Theta(n); calling removeMin() until min().getKey() > k is Θ((nk+1)log⁡n)\Theta((n_k+1)\log n) (and modifies the heap). Neither has the required cost. The entries with key ≤k\le k form a "cap" subtree T′T' over TT (by property 3 the ancestors of such an entry also have key ≤k\le k): visit only the nodes of T′T' with a preorder traversal, stopping at children with key >k> k.

Building a heap from nn entries

Goal: rearrange an array P[0..n−1]P[0..n-1] into a heap, in place. An algorithm is in-place if it uses only O(1)O(1) 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() nn times: extra space Θ(n)\Theta(n) and time Θ(nlog⁡n)\Theta(n \log n).

Solution 1: top-down, n−1n-1 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 jj (1≤j≤n−11 \le j \le n-1): P[0..j]P[0..j] is a valid heap and P[j+1..n−1]P[j+1..n-1] is still in the original order. For j=0j = 0 the root alone is a heap. Iteration j+1j+1 is an insert of P[j+1]P[j+1] into the heap P[0..j]P[0..j], so the invariant is preserved. Same as nn insertions in an empty structure, but in place.

Complexity. A heap of j+1j+1 nodes has height log⁡2(j+1)\log_2(j+1), and each insert is proportional to the height:

Θ ⁣(∑j=1n−1log⁡(j+1))=Θ ⁣(∑j=2nlog⁡j).\Theta\!\left(\sum_{j=1}^{n-1} \log(j+1)\right) = \Theta\!\left(\sum_{j=2}^{n} \log j\right).

Upper bound: log⁡j≤log⁡n\log j \le \log n for every j≤nj \le n (the logarithm is increasing), so ∑j=1nlog⁡j≤nlog⁡n\sum_{j=1}^{n} \log j \le n \log n. Starting the sum at j=1j=1 instead of j=2j=2 changes nothing since log⁡1=0\log 1 = 0. Lower bound: take only the last half of the terms, j≥⌊n/2⌋j \ge \lfloor n/2 \rfloor: each is ≥log⁡⌊n/2⌋\ge \log \lfloor n/2 \rfloor and there are about n/2n/2 of them, so

∑j=1nlog⁡j≥n2log⁡n2=n2(log⁡n−log⁡2)=Ω(nlog⁡n).\sum_{j=1}^{n} \log j \ge \frac{n}{2}\log\frac{n}{2} = \frac{n}{2}(\log n - \log 2) = \Omega(n \log n).

The bad instance is an array initially sorted in decreasing order of keys (every insertion bubbles up to the root). Hence ∑log⁡j∈Θ(nlog⁡n)\sum \log j \in \Theta(n \log n) for any constant base and the top-down construction costs Θ(nlog⁡n)\Theta(n \log n): in place, but not faster than Solution 0.

Solution 2: bottom-up, ⌊n/2⌋\lfloor n/2 \rfloor down-heap bubblings

Start from the parent of Last, P[⌊(n−2)/2⌋]P[\lfloor (n-2)/2 \rfloor] (rightmost internal node of the penultimate level), and go up to the root. The leaves (≈n/2\approx n/2 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 ⌊(n−2)/2⌋=⌊n/2⌋−1\lfloor (n-2)/2 \rfloor = \lfloor n/2 \rfloor - 1, the loop runs ⌊n/2⌋\lfloor n/2 \rfloor times, once per internal node.

Invariant at the end of iteration jj: the prefix P[0..j−1]P[0..j-1] is unchanged and the suffix P[j..n−1]P[j..n-1] is a forest of heaps. Each iteration performs a down-heap bubbling from P[j]P[j], making the subtree rooted at P[j]P[j] a valid heap (its two subtrees are already heaps).

Example. P=[2,10,27,9,11,13,5,30,18,1,14,15]P = [2, 10, 27, 9, 11, 13, 5, 30, 18, 1, 14, 15], n=12n = 12, so jj goes from 5 to 0. Applying the algorithm:

jj swap performed array after the iteration
5 none (13 ≤\le 15) [2,10,27,9,11,13,5,30,18,1,14,15][2,10,27,9,11,13,5,30,18,1,14,15]
4 11 with 1 [2,10,27,9,1,13,5,30,18,11,14,15][2,10,27,9,1,13,5,30,18,11,14,15]
3 none (9 ≤\le 30, 18) same
2 27 with 5 [2,10,5,9,1,13,27,30,18,11,14,15][2,10,5,9,1,13,27,30,18,11,14,15]
1 10 with 1 [2,1,5,9,10,13,27,30,18,11,14,15][2,1,5,9,10,13,27,30,18,11,14,15]
0 2 with 1 [1,2,5,9,10,13,27,30,18,11,14,15][1,2,5,9,10,13,27,30,18,11,14,15]

Complexity. Let h≈⌊log⁡2n⌋h \approx \lfloor \log_2 n \rfloor. A node at level ii can move down to the leaves at most, so its down-heap costs O(h−i)O(h-i); level ii has 2i2^i nodes. The loop overhead is O(n)O(n) (≈n/2\approx n/2 iterations with constant work each). So

T(n)=O ⁣(n+∑i=0h−12i(h−i)).T(n) = O\!\left(n + \sum_{i=0}^{h-1} 2^i (h-i)\right).

Claim 1. ∑ℓ=1hℓ⋅12ℓ<3\sum_{\ell=1}^{h} \ell \cdot \frac{1}{2^\ell} < 3.

Step 1: ℓ⋅12ℓ≤(34)ℓ\ell \cdot \frac{1}{2^\ell} \le \left(\frac{3}{4}\right)^\ell for all ℓ≥1\ell \ge 1, by induction. Base: ℓ=1\ell = 1: 12≤34\frac12 \le \frac34; ℓ=2\ell = 2: 24=12≤916\frac{2}{4} = \frac12 \le \frac{9}{16}. Step (ℓ≥2\ell \ge 2):

(ℓ+1)12ℓ+1=ℓ2ℓ⋅ℓ+12ℓ≤(34)ℓ⋅ℓ+12ℓ≤(34)ℓ⋅34=(34)ℓ+1,(\ell+1)\frac{1}{2^{\ell+1}} = \frac{\ell}{2^\ell} \cdot \frac{\ell+1}{2\ell} \le \left(\frac34\right)^\ell \cdot \frac{\ell+1}{2\ell} \le \left(\frac34\right)^\ell \cdot \frac34 = \left(\frac34\right)^{\ell+1},

because ℓ+12ℓ≤34  ⟺  4ℓ+4≤6ℓ  ⟺  ℓ≥2\frac{\ell+1}{2\ell} \le \frac34 \iff 4\ell + 4 \le 6\ell \iff \ell \ge 2.

Step 2: by the geometric sum and dropping the non-negative term (34)h+1\left(\frac34\right)^{h+1},

∑ℓ=1hℓ12ℓ≤∑ℓ=1h(34)ℓ=34−(34)h+11−34<3/41/4=3.□\sum_{\ell=1}^{h} \ell \frac{1}{2^\ell} \le \sum_{\ell=1}^{h} \left(\frac34\right)^\ell = \frac{\frac34 - \left(\frac34\right)^{h+1}}{1 - \frac34} < \frac{3/4}{1/4} = 3. \quad \square

Claim 2. ∑i=0h−12i(h−i)∈O(n)\sum_{i=0}^{h-1} 2^i (h-i) \in O(n).

∑i=0h−12i(h−i)=2h∑i=0h−1h−i2h−i=2h∑ℓ=1hℓ2ℓ<3⋅2h≤3n,\sum_{i=0}^{h-1} 2^i (h-i) = 2^h \sum_{i=0}^{h-1} \frac{h-i}{2^{h-i}} = 2^h \sum_{\ell=1}^{h} \frac{\ell}{2^\ell} < 3 \cdot 2^h \le 3n,

with ℓ=h−i\ell = h - i, 2h2^h independent of ii, Claim 1, and 2h≤n2^h \le n since h=⌊log⁡2n⌋h = \lfloor \log_2 n \rfloor. □\square

Hence the bottom-up construction is O(n)O(n), and since it must read every entry, Θ(n)\Theta(n).

Top-down vs bottom-up

Top-down Bottom-up
Work per level ii 2i2^i operations of cost Θ(i)\Theta(i) 2i2^i operations of cost Θ((log⁡n)−i)\Theta((\log n) - i)
Trend the deeper the level, the costlier the up-heap the deeper the level, the cheaper the down-heap
Total Θ(nlog⁡n)\Theta(n \log n) Θ(n)\Theta(n)

Both are in place.

Versione ripasso

  • Complete binary tree: levels 0..h−10..h-1 full (2i2^i nodes), last level filled left to right. nn nodes give h=⌊log⁡2n⌋h = \lfloor \log_2 n \rfloor (from 2h≤n≤2h+1−12^h \le n \le 2^{h+1}-1). 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 ≤\le children keys). Max-heap: ≥\ge. Last = rightmost node of the last level.
  • Properties: root has the min; keys along a root-leaf path are non-decreasing; ancestor ≤\le descendant (chain of parent ≤\le child); if keys are distinct, the max is at a leaf and eie_i has depth d<id < i (its dd ancestors are dd distinct smaller keys, but only i−1i-1 exist).
  • Non-decreasing arrays are heaps; the converse is false ([2,5,3,9,7][2,5,3,9,7]).
  • Level numbering: root P[0]P[0]; children P[2i+1],P[2i+2]P[2i+1], P[2i+2]; parent P[⌊(i−1)/2⌋]P[\lfloor (i-1)/2 \rfloor]; Last =P[n−1]= P[n-1]. Level ii at 2i−1≤j≤2i+1−22^i - 1 \le j \le 2^{i+1} - 2. 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 P[i]P[i] and its parent. Θ(log⁡n)\Theta(\log n).
  • removeMin: save P[0]P[0], move P[last]P[last] to the root, down-heap bubbling (swap with the smaller child while >>). Invariant: only violation is between P[i]P[i] and its smaller child. Θ(log⁡n)\Theta(\log n).
  • min() Θ(1)\Theta(1); size, isEmpty Θ(1)\Theta(1). Worst cases: insert of a new minimum, removeMin when the moved entry is the largest.
  • Remove arbitrary P[j]P[j]: put P[last]P[last] there; may need up- or down-heap bubbling.
  • Build a heap in place:
    • top-down, n−1n-1 up-heap bubblings: ∑log⁡j=Θ(nlog⁡n)\sum \log j = \Theta(n \log n) (upper bound nlog⁡nn \log n; lower bound last half of the terms);
    • bottom-up, j=⌊(n−2)/2⌋j = \lfloor (n-2)/2 \rfloor down to 0 (⌊n/2⌋\lfloor n/2 \rfloor iterations, forest-of-heaps invariant): ∑2i(h−i)=2h∑ℓ/2ℓ<3n\sum 2^i(h-i) = 2^h \sum \ell/2^\ell < 3n, so Θ(n)\Theta(n).
  • Typical mistakes: bubbling with the larger child in removeMin; using nn instead of n−1n-1 for Last; thinking bottom-up costs O(nlog⁡n)O(n \log n) tightly.

Teoria collegata