----------------------------------------------------------------------------- COMP 731 - Data Struc & Algorithms - Lecture 5 - Monday, July 3, 2000 ----------------------------------------------------------------------------- Announcements: from now on we will meet: TR 8:30-10:00 F 11-12 Today: [ ] Heaps, lecture 2 Heaps ------ Review of heaps - sort some cards, using the fast method to build a heap. Heaps are good for implementing the Priority Queue ADT - ADT Priority Queue Data: A set of items, S={x_1, ..., x_n} each item having an associated key, key(x_1), ..., key(x_n), the keys being drawn from a totally ordered universe. Initially, there are no items in the set. Operations: Insert (x): S = S U {x} Maximum (): If |S|==0 then error. Else return an items x such that key(x) is maximal among the key(x_1), ..., key(x_n) Delete-Max(): Let x be an item such that key(x) is maximal among key(x_1), ..., key(x_n). S = S \ {x} return x Applications: Job scheduling, where jobs have priorities. Event-driven simulation Many algorithms use heaps; we will see some, like Prim's algorithm and Dijkstra's algorithm. Basic operations: insert: sift up O(lg n) delete_max: sift down O(lg n) make_heap: O(1) Building a heap with n items: O(n \lg n) by way of consecutive insertions. Or ... [review method]. Analysis: lg n lg n SUM i n/2^i = n SUM (i/2^i) i = 1 i=1 An interesting sum. Let's us review some properties of sums 1 + x + x^2 + ... = 1/(1-x) (for |x|<1) (prove!) Differentiate both sides and multiply by x to get 1 + 2x^2 + 3x^3 + ... = x / (1-x)^2 (for |x|<1) (remember that (1/f)' = -f'/f^2) So, upper-bound the above by n (1/2)/(1-1/2)^2 = 2n.