D ATA S TRUCTURES II
binary heap demo
Algorithms F O U R T H E D I T I O N
R OBERT S EDGEWICK | K EVIN W AYNE
Copyright 2013 Kevin Wayne
http://www.cs.princeton.edu/~wayne/kleinberg-tardos
Last updated on Sep 8, 2013 7:00 AM
Binary heap demo
heap ordered
10 8
12 18 11 25
21 17 19
Binary heap demo
Insert. Add node at end; repeatedly exchange element in child with element
in parent until heap order is restored.
insert 7
10 8
12 18 11 25
21 17 19 7 add to heap
Binary heap demo
Insert. Add node at end; repeatedly exchange element in child with element
in parent until heap order is restored.
insert 7
10 8
12 18 11 25
violates heap order
21 17 19 7 (swim up)
Binary heap demo
Insert. Add node at end; repeatedly exchange element in child with element
in parent until heap order is restored.
insert 7
10 8
12 7 11 25
violates heap order
21 17 19 18 (swim up)
Binary heap demo
Insert. Add node at end; repeatedly exchange element in child with element
in parent until heap order is restored.
insert 7
7 8
12 10 11 25
violates heap order
21 17 19 18 (swim up)
Binary heap demo
heap ordered
7 8
12 10 11 25
21 17 19 18
Binary heap demo
Extract min. Exchange root node with last node; repeatedly exchange
element in parent with element in larger child until heap order is restored.
extract the minimum
7 8
12 10 11 25
21 17 19 18
Binary heap demo
Extract min. Exchange root node with last node; repeatedly exchange
element in parent with element in larger child until heap order is restored.
extract the minimum
7 8
12 10 11 25
21 17 19 18 exchange with root
Binary heap demo
Extract min. Exchange root node with last node; repeatedly exchange
element in parent with element in larger child until heap order is restored.
extract the minimum
18
7 8
12 10 11 25
21 17 19 6 exchange with root
Binary heap demo
Extract min. Exchange root node with last node; repeatedly exchange
element in parent with element in larger child until heap order is restored.
extract the minimum
violates heap order
18 (sink down)
7 8
12 10 11 25
21 17 19 6
Binary heap demo
Extract min. Exchange root node with last node; repeatedly exchange
element in parent with element in larger child until heap order is restored.
extract the minimum
violates heap order
7 (sink down)
18 8
12 10 11 25
21 17 19 6
Binary heap demo
Extract min. Exchange root node with last node; repeatedly exchange
element in parent with element in larger child until heap order is restored.
extract the minimum
violates heap order
7 (sink down)
10 8
12 18 11 25
21 17 19 6
Binary heap demo
heap ordered
10 8
12 18 11 25
21 17 19