In the following, the values added to the priority queue are their own priorities. What is printed by the following pseudocode? Hint: remember that “highest priority” means “smallest priority value”.
pq = new PriorityQueue();
pq.add(0)
pq.add(1)
print(pq.poll())
pq.add(2)
print(pq.peek())
pq.add(8)
print(pq.poll())
Consider the following three PriorityQueue
methods (here we’re using the A3 interface, instead of the Java one, but it doesn’t change the outcome of any of the following questions):
interface PriorityQueue<V, P extends Comparable<P>> {
boolean add(V v, P p); // add v w/ priority p
V peek(); // return highest-priority val
V poll(); // remove/return highest-priority val
}
For each data structure below, give the asymptotic runtime class of each the above three operations if you implemented the PriorityQueue interface using the specified data structure:
Once again, let’s keep things simple and assume that we’re storing Heaps of integer values that double as their own priorities.
add
each of the following values in the given order and draw (in tree form) the final heap that results:8, 7, 9, 2, 4, 10, 6
[1, 5, 7, 6, 7, 10]
Draw the tree corresponding to this heap.
Starting with the same heap from above:
[1, 5, 7, 6, 7, 10]
execute poll()
twice and write the state of the array after each call terminates.