Exercises - Lecture 12

12A

  1. 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:

  1. Linked list of values sorted by Priority
  2. Unsorted linked list
  3. Binary Search Tree
  4. AVL Tree

12B

  1. Which of the following are valid heaps?

Once again, let’s keep things simple and assume that we’re storing Heaps of integer values that double as their own priorities.

  1. Starting from an empty heap, 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. Here’s a heap, stored in an array:
[1, 5, 7, 6, 7, 10]

​ Draw the tree corresponding to this heap.

12C

  1. 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.