CP164 Study Guide - Midterm Guide: Priority Queue

58 views2 pages
14 Jun 2018
School
Course
Professor
The Array-Based Priority Queue
Implementation
Removing Items from an Array-Based Priority Queue
To remove the item with the highest priority from the _values list, you first have to find it.
That means searching the entire list for the item with the highest priority, then removing it
from the list with the pop method. The implementation of this is left to you as an exercise.
def remove(self):
"""
-------------------------------------------------------
Removes and returns the highest priority value from the priority
queue.
Use: value = pq.remove()
-------------------------------------------------------
Returns:
value - the highest priority value in the priority queue -
the value is removed from the priority queue. (?)
-------------------------------------------------------
"""
assert len(self._values) > 0, \
"Cannot remove from an empty priority queue"
# your code here
return value
Peeking at a Priority Queue
When peeking at a Priority Queue, the method should return to the user a copy of the value
with the highest priority. This implies, that as with the remove method, the highest priority
value must first be found. Such a naive algorithm is clearly very inefficient if even a single
peek is performed on a Priority Queue before an item is removed because searching for the
same item is executed at least twice. A improved solution - that does not involve sorting - is
to keep track of, or cache, the highest priority item in the Priority Queue. This results in the
following:
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers

Related Documents

Related Questions