CS 61B:
Lecture 25
Wednesday, October 25, 2006
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.
A total order is defined on the keys, and 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, suppose we 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 it is expected to take 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 _binary_heap_ is a complete binary tree.
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).
In this figure,
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.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document±
The entries in a heap satisfy the _heaporder_property_:
no child has a key
less than its parent's key.
Observe that any 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,
This is the end of the preview. Sign up
to
access the rest of the document.
This note was uploaded on 04/20/2010 for the course CS CS206 taught by Professor Lee during the Fall '09 term at 카이스트, 한국과학기술원.
 Fall '09
 Lee

Click to edit the document details