Bin Heaps
Bin Heaps
Chapter 19
Heap
• Under most circumstances you would use
a “normal” binary heap
• Except some algorithms that may use
heaps might require a “Union” operation
– How would you implement “Union” to merge
two binary heaps?
Heap Runtime
Binomial Heaps
The binomial tree Bk is an ordered tree
defined recursively.
B0
B1
Bo
Bo
B2
B1
B1
Binomial Trees
B3
B2
B2
B4
B3
B3
Binomial Trees
In general:
Bk Bk-1
Bk-1
4 0
B2 2 bits B3 3 bits
1 11 1 111
101
01 3 2 10 100 6 3 2 110
00 4 001 7 8 4 011
010
000 9
Binomial Heaps
Representing a Binomial Heap with 14 nodes
Head 2 1 1
<1110> 4 3 2 6 3 9
4 8 7 4
Parent
t
Paren rent
a P
Sibling Sibling
i ld
Ch t
r en
Parent
Pa
Parent
Sibling Sibling
Child
Parent
Create New Binomial Heap
• Just allocate an object H, where
head[H] = NIL
• Θ(1) runtime
Binomial Min-Heap
• Walk across roots, find minimum
• O(lg n) since at most lg n + 1 trees
Head 2 1 3
4 3 2 6 4 9
4 8 7 6
9
1.
2.
p[y] z
sibling[y] child[z]
Binomial-Link(y,z)
3. child[z] y z
4. degree[z] degree[z] + 1 z becomes the
y parent of y
Link binomial trees with the same
degree. Note that z, the second
argument to BL(), becomes the parent,
and y becomes the child. z
y z y
Θ(1) Runtime
Binomial-Heap-Union(H1, H2)
1. H Binomial-Heap-Merge(H1, H2)
This merges the root lists of H1 and H2 in increasing order of
root degree
2. Walk across the merged root list, merging binomial
trees of equal degree. If there are three such trees in
a row only merge the last two together (to maintain
property of increasing order of root degree as we walk
the roots)
2 60 80 18
32 63 93 58 19
53 69
53 69
60 80 2
Combine trees of same degree
using binomial link, make
93 18 32 63
smaller key the root of the
combined tree
58 19 53
69
Binomial-Heap-Insert(H)
To insert a new node, simple create a new Binomial
Heap with one node (the one to insert) and then
Union it with the heap
1. H’ Make-Binomial-Heap()
2. p[x] NIL
3. child[x] NIL
4. sibling[x] NIL
5. degree[x] 0
6. head[H’] x
7. H Binomial-Heap-Union(H, H’)
Runtime: O(lg n)
Binomial-Heap-Extract-Min(H)
With a min-heap, the root has the least value in the heap.
Notice that if we remove the root from the figure below, we are left with four
heaps, and they are in decreasing order of degree. So to extract the min we
create a root list of the children of the node being extracted, but do so in
reverse order. Then call Binomial-Heap-Union(..)
Reversal of
roots, and
Runtime: Θ(lg n) combining into
new heap
Heap Decrease Key
• Same as decrease-key for a binary heap
– Move the element upward, swapping values,
until we reach a position where the value is
key of its parent
Runtime: Θ(lg n)
Heap Delete Key
• Set key of node to delete to –infinity and
extract it:
Runtime: Θ(lg n)