10/25/10
16:36:27
1
25
CS 61B: Lecture 25
Monday, October 25, 2010
Today’s reading:
PRIORITY QUEUES
===============
A priority queue, like a dictionary, contains _entries_ that each consist of
a key and an associated value.
However, whereas a dictionary is used when we
want to be able to look up arbitrary keys, a priority queue is used to
prioritize entries.
Define a total order on the keys (e.g. alphabetical
order).
You may identify or remove the entry whose key is the lowest (but no
other entry).
This limitation helps to make priority queues fast.
However, an
entry with any key may be inserted at any time.
For concreteness, let’s use Integer objects as our keys.
The main operations:
 insert() adds an entry to the priority queue;
 min() returns the entry with the minimum key; and
 removeMin() both removes and returns the entry with the minimum key.
5




4: womp
v
4: womp


7: gonginsert(k, v)>7: gongremoveMin()>7: gongmin()


^
5: hoot

5: hoot




v

v
hoot
(4, womp)
(5, hoot)
Priority queues are most commonly used as "event queues" in simulations.
Each
value on the queue is an event that is expected to take place, and each key
is the time the event takes place.
A simulation operates by removing
successive events from the queue and simulating them.
This is why most
priority queues return the minimum, rather than maximum, key:
we want to
simulate the events that occur first first.
public interface PriorityQueue {
public int size();
public boolean isEmpty();
Entry insert(Object k, Object v);
Entry min();
Entry removeMin();
}
Binary Heaps:
An Implementation of Priority Queues

A _complete_binary_tree_ is a binary tree in which every row is full, except
possibly the bottom row, which is filled from left to right as in the
illustration below.
Just the keys are shown; the associated values are
omitted.
2
index:
0
1
2
3
4
5
6
7
8
9
10
/ \
/
\

5
3

 2  5  3  9  6  11  4  17  10  8 
/ \
/ \

9
6 11
4
^
/ \ /

17 10 8
\ array index 0 intentionally left empty.
A _binary_heap_ is a complete binary tree whose entries satisfy the
_heaporder_property_:
no child has a key less than its parent’s key.
Observe that every subtree of a binary heap is also a binary heap, because
every subtree is complete and satisfies the heaporder property.
Because they are complete, binary heaps are often stored as arrays of entries,
ordered by a levelorder traversal of the tree, with the root at index 1.
This
mapping of tree nodes to array indices is called _level_numbering_.
Observe that if a node’s index is i, its children’s indices are 2i and 2i+1,