Heaps

Heaps - o can have duplicate key values k’s left child:...

This preview shows pages 1–2. Sign up to view the full content.

Heaps Heap -- used for 2 things 1. used to implement priority queue a. e.g. CPU, airplanes taking off b. dequeue gets object with highest priority b.i. [O1| P1], [O2| P2], [O3| P3] 2. for sorting -- heapsort How to implement a heap? possibility #1: priority queue using sorted LL a; 1, b; 0, c; 2 big O 1. enqueue -- O(n) 2. deqeuue -- O(1) possibility #2: unsorted LL 1. enqueue -- O(1) 2. dequeue -- O(n) possibility #3: AVL tree keyed on priorities 1. enqueue (Object, p) // p is the key a. insert -- O (log n) 2. dequeue a. find highest priority item (all the way to the right) -- O(log n) better than LL option! however it is too complicated… heap structure - structure property : binary tree in which all levels except the last are full , and the last level is filled left to right without gaps o can’t go to the next level unless the levels above are all full o can’t go right without the left being filled up first o O(log n) - ordering property : key at any node x is keys at its children o different than a BST or AVL tree definitions o right children key can be less than left children key

This preview has intentionally blurred sections. Sign up to view the full version.

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

Unformatted text preview: o can have duplicate key values k’s left child: 2k+1 k’s right child: 2k+2 k’s parent: (k-1)/2 [see notes on paper] Sift up-compare with parent o if > parent, switch & move up to next level, then repeat o else, quit Sift down-compare the two children, pick the largest one and swap with parent o while index is not out of bound, switch & move down a level, then repeat o else, quit Heap running time (worst case) • Insert - O(log n) o counting number of comparisons in sift up o if height of the heap is h number of comparisons is h what is h as a function of n? • delete - O(log n) o counting number of comparisons in sift down for running time o if height of heap is h number of comparisons is 2h Use heap for sorting -- heap sort 5 1 3 1 8 2 2 6 insert in a heap, one at a time 1 st delete -> 22 2 nd delete -> 18 running time • insert o O(log n!) = O(n log n) • delete o O(log n!) = O(n log n)...
View Full Document

This note was uploaded on 03/29/2012 for the course CS 112 taught by Professor Sesh during the Spring '07 term at Rutgers.

Page1 / 2

Heaps - o can have duplicate key values k’s left child:...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online