Priority Queues and Heaps_Part_4

Priority Queues and Heaps_Part_4 - k Since a heap has...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
Last Updated: 06/02/12 8:32 PM CSE 2011 Prof. J. Elder - 16 - Removal from a Heap Method removeMin of the priority queue ADT corresponds to the removal of the root key from the heap The removal algorithm consists of three steps Replace the root key with the key of the last node w Remove w Restore the heap-order property 2 6 5 7 9 last node w 7 6 5 9 w new last node
Background image of page 1

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

View Full DocumentRight Arrow Icon
Last Updated: 06/02/12 8:32 PM CSE 2011 Prof. J. Elder - 17 - Downheap After replacing the root key with the key k of the last node, the heap-order property may be violated Algorithm downheap restores the heap-order property by swapping key k along a downward path from the root Note that there are, in general, many possible downward paths – which one do we choose? 7 6 5 9 w ? ?
Background image of page 2
Last Updated: 06/02/12 8:32 PM CSE 2011 Prof. J. Elder - 18 - Downheap We select the downward path through the minimum-key nodes. Downheap terminates when key k reaches a leaf or a node whose children have keys greater than or equal to
Background image of page 3

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

View Full DocumentRight Arrow Icon
Background image of page 4
Background image of page 5
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: k Since a heap has height O (log n ) , downheap runs in O (log n ) time 7 6 5 9 w 5 6 7 9 w Last Updated: 06/02/12 8:32 PM CSE 2011 Prof. J. Elder - 19 - Array-based Heap Implementation We can represent a heap with n keys by means of an array of length n + 1 Links between nodes are not explicitly stored The cell at rank is not used The root is stored at rank 1. For the node at rank i the left child is at rank 2 i the right child is at rank 2 i + 1 the parent is at rank floor (i/2) if 2i + 1 > n, the node has no right child if 2i > n, the node is a leaf 2 6 5 7 9 2 5 6 9 7 1 2 3 4 5 Last Updated: 06/02/12 8:32 PM CSE 2011 Prof. J. Elder - 20 - Merging Two Heaps We are given two heaps and a new key k We create a new heap with the root node storing k and with the two heaps as subtrees We perform downheap to restore the heap-order property 7 3 5 8 2 6 4 3 5 8 2 6 4 2 3 5 8 4 6 7...
View Full Document

This note was uploaded on 02/14/2012 for the course CSE 2011Z taught by Professor Elder during the Fall '11 term at York University.

Page1 / 5

Priority Queues and Heaps_Part_4 - k Since a heap has...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online