
Computer Science II — CSci 1200
Lecture 21
Priority Queues and Heaps
Today’s Class
•Idea of a priority queue
•A priority queue as a heap — a complete binary tree
•Percolate up and percolate down operations
•A heap as a vector
•Making a heap
•Heap sort
Priority Queue — Fundamental Operations
•Priority queues are used in prioritizing operations. Examples include jobs on a shop
floor, packet routing in a network, scheduling in an operating system, or events in a
simulation.
•Among the data structures we have studied, their interface is most similar to a queue,
including the idea of a front or top and a tail or a back.
•Each item is stored in a priority queue using an associated “priority” and therefore,
the top item is the one with the lowest value of the priority score.
–The tail or back is never accessed through the interface to a priority queue.
•The main operations are insert or push, and pop (or delete_min).
Data Structure Options
•Vector or list, either sorted or unsorted
–Here at least one of the operations, push or pop, will cost linear time, at least if
we think of the container as a linear structure.
•Binary search trees
–If we use the priority as a key, then we can use a combination of finding the
minimum key and erase to implement pop. An ordinary binary-search-tree insert
may be used to implement push.
–This costs logarithmic time in the average case (and in the worst case as well if
balancing is used).
•The latter is the better solution, but we would like to improve upon it — for example,
it might be more natural if the minimimum priority value were stored at the root.
–We will achieve this using a “heap”, giving up the complete ordering imposed in
the binary search tree.