Notes for week 8 lecture on the heap implementation of priority queues (ODS chapter 10)
----[ Mon, Apr 7 ]----
The (min) Priority Queue interface (it was introduced in chapter 1):
- 
A priority queue of objects of type T requires that the compare function is defined
on objects of type T.  For instance, this definition of compare allows T to be any numeric type.
 
template<typename T>
 int compare (T a, T b) {
 if (a < b) return -1;
 if (a == b) return 0;
 if (a > b) return 1;
 }
 Another compare function sketched.
-  The interface specifies these functions
 
 
int size(); // return the current size of the queue.
 
 void add(T x); // add x to the queue.
 
 T remove(); // Remove and return the minimal element of the queue.
 // Requires a nonempty queue.
 // The "remove" function is often called "extractMin".
How to implement priority queues?  Let's try a couple of ideas.
Let n be the current size of the priority queue.
-  Idea 1: be totally disorganized, maintain an unsorted array.
-  add(x) is ArrayDeque::add(n, x)
-  remove(x) is find location k of min, then ArrayDeque::remove(k)
-  Costs are O(1), O(n) respectively.
 
-  Idea 2: be totally organized, maintain a sorted array.
-  add(x) is ArrayDeque::add(0, x), then bubble it up to proper sorted position.
-  remove(x) is ArrayDeque::remove(0)
-  Costs are O(n), O(1) respectively.
 
-  Idea 3: be semi-organized, maintain an array with the heap property.
-  add(x) is ArrayStack::add(n, x), then bintree bubble up 
-  remove(x) is swap first and last, then trickle down
-  Costs will be O(log(n)), O(log(n)) respectively.
 
A  heap  has 3 key properties.
-  It is a left-complete binary tree.
-  It is a binary tree with the heap property: Value at a node is less than (or equal to) the values at it's children (if any).
-  It's storage is an array.  We exploit two views: as binary tree, as array.
Illustration,
ODS Chapter 10
Implementation:
BinaryHeap.h.
Another example.