notes_COSqueues

Take nodes in level order no explicit links needed 8e

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: S T Array representation. 1 T 5N 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 R P N S 5 N E I public void insert(Key x) { pq[++N] = x; swim(N); } R P private void swim(int k) { while (k > 1 && less(k/2, k)) { exch(k, k/2); 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 N E H O A key to insert H I G O S T swim up A A add key to heap violates heap order R S N G T T 2 H 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; exch(k, j); k = j; } } remove the maximum T violates heap order (smaller than a child) 2 E T R H 5 P I public Key delMax() E I { Key max = pq[1]; exch(1, N--); P sink(1); pq[N+1] = null; N return max; E I } S N O A G T 2 5 P E R S I 10 H N O A H G O 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 O 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. Heap operations 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.

Ask a homework question - tutors are online