1.16k likes | 1.39k Views
Heaps and Priority Queues Basic idea in this chapter: We prioritize data structures for special purposes Heap is a kind of tree structure Use a heaps to implement a priority queue. Content. Motivation: the need for priority queuing ? Fair/unfair? Background (queues and tree structures)
E N D
Heaps and Priority QueuesBasic idea in this chapter: We prioritize data structures for special purposes Heap is a kind of tree structureUse a heaps to implement a priority queue
Content • Motivation: the need for priority queuing ? Fair/unfair? • Background (queues and tree structures) • What is a heap • Heap types: Leftist, Binomial, d-type, skew • Merging two heaps • Analysis and implementation details Dr.Alagoz
Priority Queue (Heaps) • Priority Queue is a data structure allowing at least the following two operations: • insert same like enqueue in nonpriority queues • deleteMin is the priority queue equivalent of queue’s dequeu operation(i.e. find and remove the minimum element in prioritized queue) • Efficient implementation of priority queue ADTs • Uses and implementation of priority queues Dr.Alagoz
Priority Queue: Applications • External sorting • Discrete-event simulations • Very important for greedy algorithms (CHP9) and optimization problems (CHP10) • Example: ARAM system is greedy!!! Dr.Alagoz
Motivation … Problem 1 4 2 • Queue: the fancy name for waiting in line Dr.Alagoz
Motivation … Problem - At the Bank, bust stop 1 4 2 • Queue at the counter or bus stop • Give priority to • Elderly • Pregnant • With baby • … Dr.Alagoz
Motivation … Problem – Hospital 1 4 2 • Patients waiting for help in Emergency Room • Give priority to • Severely wounded • Bleading • … • the ones with crash !!! Dr.Alagoz
Motivation … Problem - Operating System 1 4 2 • Processes waiting for services • Printer • Multiuser environment • CPU • Give priority to • I/O bound • Interrups • Eg. small jobs(1page print) may be given priority over large jobs (100pages) … Dr.Alagoz
Review of Queues Dr.Alagoz
Review Queue 1 4 2 publicinterface Queue extends Container { Object getHead(); void enqueue(Object object); Object dequeue(); } FIFO • first come • first serve • One entry place • One exit place • No change in order • No priority • ARAM system is priority based!!! G/G/m/K • General arrival process time • General service process time • m servers • K buffer size • Example M/M/1: Exponential arrival time Exponential service time Single server queue Dr.Alagoz
Review Queue ADT… dequeque() enqueque(4) enqueque(2) dequeque() enqueque(3) dequeque() dequeque() dequeque() enqueque(1) enqueque(1) 2 3 1 1 1 4 1 4 2 1 4 2 3 4 2 3 1 2 3 1 1 3 1 1 1 1 2 3 Sample operation Dr.Alagoz
Review Queue …Priorities- a few a1 a4 b3 b1 b27 b3 b3 c6 c4 c9 • If there is a need for change in the order • One queue for each priority Algorithm • enqueue • put in to proper queue • dequeue • get from P1 first • then get from P2 • then get from P3 P1 P2 P3 Dr.Alagoz
Review Queue …Priorities- more 7 12 41 a1 a4 b3 b1 b27 b3 b3 c6 c4 c9 • If there is a need for change in the order • One queue for each priority • Number of different priority categories is known Algorithm • enqueue • put in to proper queue • dequeue • get from P1 first • then get from P2 • then get from P3 • … • then get from P123 P1 P2 P3 . . . P123 Dr.Alagoz
Review Queue …Priorities– too many 7 12 41 a1 a4 b3 b1 b27 b3 b3 c6 c4 c9 • If there is a need for change in the order • One queue for each priority • Number of different priority categories is unknown Algorithm • enqueue • put in to proper queue • dequeue • get from P1 first • then get from P2 • then get from P3 • … • then get from P123 P1 P2 P3 . . . P123 Dr.Alagoz
Priority Queues Dr.Alagoz
Priority Queues …Abstractions • Priority queue • A list of items • Each item has an associated priority • Insertion • Arbitrary order • Arbitrary priority • Deletion • Item with the lowest (highest) priority Dr.Alagoz
Priority Queues … Abstract Operations • enqueue • Puts an object in the container • findMin • Returns a reference to the smallest object in the container • dequeueMin • Removes the smallest object from the container Dr.Alagoz
Simple Implementationsfor priority queuea) Simple link list b) Binary search tree Dr.Alagoz
Simple Implementations … Using Simple Link Lists • Link is Unsorted Array • Insert at the front in O(1) • Delete after searching the min in O(n) • Link is Sorted Array • Insert in the order in O(n) • Delete at the end in O(1) • Not: Use Unsorted Array, when there are more insertions than deleteMin. Dr.Alagoz
Simple Implementations … Using Binary Search Tree a b c • Average running time for Insert • O (log n) • Average running time for Deletion • O (log n) Now, lets talk about the heaps in class hierarchy Dr.Alagoz
HeapA heap is a binary tree storing keys at its nodesIn order to understand the heap structures lets review general tree structures Dr.Alagoz
ReviewN-ary Tree Definition An N-ary tree T is a finite set of nodes with the following properties: • Either the set is empty, T = ; or • The set consists of a root, R, and exactly N distinct N-ary trees. That is, the remaining nodes are partitioned into N0 subsets,T0 , T1, … , TN-1 , each of which is an N-ary tree such that T = {R , T0 , T1, … , TN-1 }. RemarkThe empty tree, T = , is a tree DefinitionThe empty trees are called external nodes because they have no subtrees and therefore appear at the extremities of the tree. Conversely, the non-empty trees are called internal nodes. Dr.Alagoz
Heap R1 R2 RN R Definition A (Min) Heap is a tree,T = {R , T0 , T1, … , Tn-1 }with the following properties: • Every subtree of T is a heap; and, • The root of T is less than or equal to the root of every subtree of T. That is, R Ri for all i, 0 i n , where Ri is the root of Ti . … Observations • Each node is less then all the subtrees of it. • No restrictions for the relative ordering of the subtrees. Dr.Alagoz
Binary Heap Dr.Alagoz
RecapPerfect Binary Tree Definition A perfect binary tree of height h0 is a binary tree T = {R, TL, TR} with the following properties: • If h = 0, TL = and TR = . • If h > 0, thenTL is a perfect binary tree of height h-1. TR is a perfect binary tree of height h-1. TheoremA perfect binary tree of height h has exactly 2h+1 - 1 nodes. TheoremThe height of a perfect binary tree with n internal nodes is log (n+1). Dr.Alagoz
Complete Binary Tree Definition A complete binary tree of height h0, is a binary tree T={R, TL, TR} with the following properties: • If h=0, TL = and TR = . • For h>0 there are two possibilities: • TL is a perfect binary tree of height h-2 and TR is a complete binary tree of height h-1 • TL is a complete binary tree of height h-1 and TR is a perfect binary tree of height h-2. Dr.Alagoz
Complete Binary Tree … • 1 • 1L • 2L • 2R is a complete binary tree of height 2 • 5L is a perfect binary tree of height 1 • 5R is a perfect binary tree of height 0 • 1R 2R 5L 5R Dr.Alagoz
Complete Binary Tree … 1L 2L 2R • 1 • 1L is a complete binary tree of height 3 (2a) • 2L is a perfect binary tree of height 2 • 2R is a complete binary tree of height 2 • 5L is a perfect binary tree of height 1 • 5R is a perfect binary tree of height 0 • 1R Dr.Alagoz
Complete Binary Tree … • 1 is a complete binary tree of height 4 (2b) • 1L is a complete binary tree of height 3 (2a) • 2L is a perfect binary tree of height 2 • 2R is a complete binary tree of height 2 • 5L is a perfect binary tree of height 1 • 5R is a perfect binary tree of height 0 • 1R is a perfect binary tree of height 2 1L 1R Dr.Alagoz
Complete Binary Tree …Array representation a b c b = 2a c = 2a+1 a = b/2 a = c/2 Dr.Alagoz
Complete Binary Tree … Theorem A complete binary tree of height h0 contains at least 2h and at most 2h+1 - 1 nodes. Dr.Alagoz
Complete Binary Tree … Theorem The internal path length of a binary tree with n nodes is at least as big as the internal path length of a complete binary tree with n nodes. Definition The internal path length of a tree is simply the sum of the depths (levels) of all the internal nodes in the tree di is the depth of the ith node n is the number of nodes Dr.Alagoz
Complete N-ary Tree Informally • a complete tree is a tree in which • all the levels are full except for the bottom level and • the bottom level is filled from left to right. Dr.Alagoz
Complete N-ary Tree … Definition A complete N-ary tree of height h0, is an N-ary tree T = {R , T0 , T1, … , TN-1 }with the following properties • If h=0, Ti = for all i, 0 i < N. • For h>0 there exists a j, 0 j < N such that a. Ti is a perfect binary tree of height h-1 for all i, 0 i < j b. Tj is a complete binary tree of height h-1 c. Ti is a perfect binary tree of height h-2 for all i, j<i<N Dr.Alagoz
Complete N-ary Tree … Array Representation c1 c2 cN i 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Children of node i c1 = N(i-1)+2 c2 = N(i-1)+3 c3 = N(i-1)+4 … cN = Ni+i Parent of node i (i-1)N … Dr.Alagoz
A heap is a binary tree storing keys at its nodes and satisfying the following properties: Heap-Order: for every internal node v other than the root,key(v)key(parent(v)) Complete Binary Tree: let h be the height of the heap for i = 0, … , h - 1, there are 2i nodes of depth i at depth h- 1, the internal nodes are to the left of the external nodes The last node of a heap is the rightmost node of depth h Heaps (§) 2 5 6 9 7 last node Dr.Alagoz
Height of a Heap (§) • Theorem: A heap storing nkeys has height O(log n) Proof: (we apply the complete binary tree property) • Let h be the height of a heap storing n keys • Since there are 2i keys at depth i=0, … , h - 1 and at least one key at depth h, we have n1 + 2 + 4 + … + 2h-1 + 1 • Thus, n2h, i.e., hlog n depth keys 0 1 1 2 h-1 2h-1 h 1 Dr.Alagoz
Heaps and Priority Queues • We can use a heap to implement a priority queue • We store a (key, element) item at each internal node • We keep track of the position of the last node • For simplicity, we show only the keys in the pictures (2, Sue) (5, Pat) (6, Mark) (9, Jeff) (7, Anna) Dr.Alagoz
Method insertItem of the priority queue ADT corresponds to the insertion of a key k to the heap The insertion algorithm consists of three steps Find the insertion node z (the new last node) Store k at z Restore the heap-order property (discussed next) Insertion into a Heap (§) 2 5 6 z 9 7 insertion node 2 5 6 z 9 7 1 Dr.Alagoz
Upheap (percolate up) • After the insertion of a new key k, the heap-order property may be violated • Algorithm upheap restores the heap-order property by swapping k along an upward path from the insertion node • Upheap terminates when the key k reaches the root or a node whose parent has a key smaller than or equal to k • Since a heap has height O(log n), upheap runs in O(log n) time 2 1 5 1 5 2 z z 9 7 6 9 7 6 Dr.Alagoz
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 (discussed next) 2 5 6 w 9 7 last node 7 5 6 w 9 new last node Dr.Alagoz
Downheap (percolate down) • 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 • Upheap terminates when key k reaches a leaf or a node whose children have keys greater than or equal to k • Since a heap has height O(log n), downheap runs in O(log n) time 7 5 5 6 7 6 w w 9 9 Dr.Alagoz
Updating the Last Node • The insertion node can be found by traversing a path of O(log n) nodes • Go up until a left child or the root is reached • If a left child is reached, go to the right child • Go down left until a leaf is reached • Similar algorithm for updating the last node after a removal • http://people.ksp.sk/~kuko/bak/index.html Dr.Alagoz
Consider a priority queue with n items implemented by means of a heap the space used is O(n) methods insert and removeMin take O(log n) time methods size, isEmpty, and min take time O(1) time Using a heap-based priority queue, we can sort a sequence of n elements in O(n log n) time The resulting algorithm is called heap-sort Heap-sort is much faster than quadratic sorting algorithms, such as insertion-sort and selection-sort Heap-Sort (§) Other Sorting types will be visited in CHP7 Dr.Alagoz
Vector-based Heap Implementation (§) 2 5 6 9 7 0 1 2 3 4 5 • We can represent a heap with n keys by means of a vector of length n +1 • For the node at rank i • the left child is at rank 2i • the right child is at rank 2i +1 • Links between nodes are not explicitly stored • The cell of at rank 0 is not used • Operation insert corresponds to inserting at rank n +1 • Operation removeMin corresponds to removing at rank n • Yields in-place heap-sort 2 5 6 9 7 Dr.Alagoz
Merging Two Heaps • We are given two two heaps and a 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 3 2 8 5 4 6 7 3 2 8 5 4 6 2 3 4 8 5 7 6 Dr.Alagoz
Bottom-up Heap Construction (§) 2i -1 2i -1 • We can construct a heap storing n given keys in using a bottom-up construction with log n phases • In phase i, pairs of heaps with 2i -1 keys are merged into heaps with 2i+1-1 keys 2i+1-1 Dr.Alagoz
Priority Queues … Priority Queue Interface publicinterface PriorityQueue extends Container { void enqueue(Comparable object); Comparable findMin(); Comparable dequeueMin(); } • enqueue • Puts an object in the priorityQueue • findMin • Returns a reference to the smallest object in the priorityQueue • dequeueMin • Removes the smallest object from the priorityQueue Dr.Alagoz
Priority Queues … Mergeable Priority Queue Interface public interface MergeablePriorityQueue extends PriorityQueue{ void merge(MergeablePriorityQueuequeue); } Dr.Alagoz
Priority Queues … Mostly used Heap types • Binary Heap • d-heaps • Leftist Heap • Binomial Heap • Others include skew heaps, fibonacci heaps, soft heap etc Dr.Alagoz