notes_COSqueues

# Implementation a a a a a a p m p p p l l l e e q p p

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

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: plementation A A A A A A P M P P P L L L E E Q P P P E E E E E E E public UnorderedArrayMaxPQ(int capacity) { pq = (Key) new Comparable[capacity]; Q X P M M M L E E no generic array creation } public boolean isEmpty() { return N == 0; } X P P P M L L public void insert(Key x) { pq[N++] = x; } X P P M M P P P public Key delMax() { int max = 0; for (int i = 1; i < N; i++) if (less(max, i)) max = i; exch(max, N-1); should null out entry return pq[--N]; to prevent loitering } P A sequence of operations on a priority queue less() and exch() similar to sorting methods (but don't pass pq) } 9 10 Priority queue elementary implementations Challenge. Implement all operations efficiently. 2.4 P RIORITY Q UEUES order of growth of running time for priority queue with N items implementation insert del max max unordered array 1 N N ordered array N 1 1 goal log N log N log N ‣ API and elementary implementations ‣ binary heaps Algorithms R OBERT S EDGEWICK | K EVIN W AYNE http://algs4.cs.princeton.edu 11 ‣ heapsort ‣ event-driven simulation Complete binary tree A complete binary tree in nature Binary tree. Empty or node with links to left and right binary trees. Complete tree. Perfectly balanced, except for bottom level. complete tree with N = 16 nodes (height = 4) Property. Height of complete tree with N nodes is ⎣ྏlg N⎦ྏ. Pf. Height only increases when N is a power of 2. 13 14 Binary heap representations Binary heap properties Binary heap. Array representation of a heap-ordered complete binary tree. Proposition. Largest key is a[1], which is root of binary tree. Heap-ordered binary tree. Proposition. Can use array indices to move through tree. ・ ・Parent's key no smaller than ・Parent of node at k is at k/2. ・Children of node at k are at 2k and 2k+1. Keys in nodes. children's keys. i a[i] 0 - 1 T 2 S 3 R S 4 P 5 N 6 O 7 A 8 E 9 10 11 IHG i a[i] 0 - R P N 1 9I O 4 P R 5 N 6 O 7 A P A E I H G N O A 1 T 3R 2S 4P 3 R 8 E 9 10 11 IHG E I T ・Indices start at 1. ・Take nodes in level order. ・No explicit links needed! 8E 2 S...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online