Lecture 21: Heaps and PQs

10/14/2020

The Priority Queue Interface

The Priority Queue Interface

/** (Min) Priority Queue: Allowing tracking and removal of the * smallest item in a priority queue */ public interface MinQP<Item> { // Adds the item to the priority queue public void add(Item x); // Returns the smallest item in the priority queue public Item getSmallest(); // Removes the smallest item from the priority queue public Item removeSmallest(); // Returns the size of the priority queue public int size(); }

Usage example: Unharmonious Text

Naive Implementation: Store and Sort

Better Implementation: Track the M Best

How Would we Implement a MinPQ?

Heaps

Introducing the Heap

What Good are Heaps?

How Do We Add to a Heap?

Heap Operations Summary

Tree Representations

How do we represent a tree in Java?

public class Tree1A<Key> { Key k; Tree1A left; Tree1A middle; Tree1A right; }
public class Tree1B<Key> { Key k; Tree1B[] children; ... }
// Sibling tree public class Tree1C<Key> { // Nodes at the same level point to each other's siblings Key k; Tree1C favoredChild; Tree1C sibling; }
public class Tree2<Key> { Key[] keys; int[] parents; ... }

public class Tree3<Key> { Key[] keys; }

A Deep Look at Approach 3

public void swim(int k) { if (keys[parent(k)] > keys[k]) { swap(k, parent(k)); swim(parent(k)); } }
public int parent(int k) { if (k == 0) { return 0; } return (k - 1) / 2; }

Approach 3B (book implementation): Leaving One Empty Spot in the Front

Heap Implementation of a Priority Queue

Some Implementation Questions

Data Structures Summary

The Search Problem

Search Data Structures (The particularly abstract ones)

Data Structures

Summary

Discussion Summary: Heaps