09-303 Heaps
09-303 Heaps
CMPS 303
Dr. Saeed Salem
Unit 9
Priority Queues & Heap
Some slide are adopted from slides by Dr. Saleh Alhazbi and Dr. Osama Halabi
© 2011 The McGraw-Hill Companies, Inc. Copyright © 2004 Pearson Education, Inc.
All rights reserved Publishing as Pearson Addison-Wesley
Why Priority Queues?
First-in first-out queue is not suitable for some applications.
For example
1- scheduling patients for treatment in the ER:
Patients should be scheduled based on the level of emergency. A gunshot victim
should be treated sooner than a guy with a cold, regardless of arrival time.
2- Printing jobs:
assume the printer should print jobs based on the importance of the employees in
the company (managers before employees).
So we need another type of queue where every entity must have a priority
factor to be used when queueing these entities. This type of queues is
called priority queue.
Priority Queue
Implementation
Priority Queue Implementation
1- Using unsorted array
Array will hold queue entries (each entry has a priority).
7 4 9 2 8 3
The complexity of adding an element is O(1)
because we have to search for the entry with max value to be removed, and
when removing , all elements after that one should be shifted.
9 8 5 3 2
But this might violate the heap property (parent’s key should be greater than or
equal its children’s keys), so we need to restore this property (upheap process)
Algorithm downheap restores the heap-order property by swapping key k along a downward
path from the root.
Data Structures CMPS 303 13
Efficiency of inserting and removing from heap
Heap Implementation
Heap Implementation
19 19 19 19
15 19
15 15 10 15 10 17 10 17 16
7 7 15 7 15 10
✤ Complexity of step 2:
✦ Complexity of removing min. from the heap is O(log n)
✦ Therefore removing all elements will be O(n log n)
End of
Heaps