This preview shows page 1. Sign up to view the full content.
Unformatted text preview: S T Array representation. 1
10 H 6O 7A 4P
8E Heap representations 9I G 3R 2S 11 G H T 5N
10 H 6O 7A 11 G Heap representations
15 16 Promotion in a heap Insertion in a heap Scenario. Child's key becomes larger key than its parent's key. Insert. Add node at end, then swim it up.
Cost. At most 1 + lg N compares.
insert To eliminate the violation: ・Exchange key in child with key in parent.
・Repeat until heap order restored. remove T
S 5 N
E I public void insert(Key x)
pq[++N] = x;
} R P private void swim(int k)
while (k > 1 && less(k/2, k))
k = k/2;
parent of node at k is at k/2
} T H O A
violates heap order
(larger key than parent) G E 1 E 5P I O
S R P
E H O A key to insert H
I G O
T swim up A A
add key to heap
violates heap order R S N G T T
I R S G N P O sink down
A Bottom-up reheapify (swim) E I G H
Heap operations Peter principle. Node promoted to level of incompetence.
17 18 Demotion in a heap Delete the maximum in a heap Scenario. Parent's key becomes smaller than one (or both) of its children's. Delete max. Exchange root with node at end, then sink it down.
Cost. At most 2 lg N compares. To eliminate the violation: why not smaller child?
insert ・Exchange key in parent with key in larger child.
・Repeat until heap order restored. R P
N private void sink(int k)
children of node at k
while (2*k <= N)
are 2k and 2k+1
int j = 2*k;
if (j < N && less(j, j+1)) j++;
if (!less(k, j)) break;
k = j;
} remove the maximum T violates heap order
(smaller than a child)
2 E T
I public Key delMax()
Key max = pq;
pq[N+1] = null;
} S N O A G
T 2 5 P
E R S I 10 H N O A H
S E key to insert P
I G R G S R E P
I G P
G O A remove node
from heap T
S R N violates
heap order S
N add key to heap
violates heap order A exchange key
with root H T I O H S E N prevent loitering
A swim up G Top-down reheapify (sink) R S
A T H key to remove T O R P sink down
N A H E H
I O A G Power struggle. Better subordinate promoted.
19 20 Binary heap demo Binary heap demo Insert. Add node at end, then swim it up. Insert. Add node at end, then swim it up. Remove the maximum. Exchang...
View Full Document
This document was uploaded on 02/20/2014 for the course COS 226 at Princeton.
- Fall '08