This class implements a general purpose heap. The element type T and the ordering function (via class Cmp) are passed in as parameters to the Heap template.
This heap sifts the LARGEST elements to the top and the SMALLEST elements to the bottom, according tho the comparison function, Cmp.gt(). Thus the "heap property" is that value(Parent(i)) gt value(i) for each element i in the heap.
An element anywhere in the heap can be changed (by an outsider- not by the heap template) and the heap property can be restored, but he who changes the element must know whether the element's key value increased or decreased. Since we're sifting "large" elements to the top of the heap, if the element's key value increases, the element must be sifted UP, and if its value decreases, it must be sifted down. The methods IncreaseN and DecreaseN handle these cases.
The heap has the following worst case run times:
The comparison class, Cmp, must have the member functions gt (T* left, T* right) returns true iff left > right
RemoveFirst always removes the largest element.
Definition at line 79 of file w_heap.h.
Public Member Functions | |
Heap (const Cmp &cmpFunction, int initialNumElements=32) | |
~Heap () | |
int | NumElements () const |
How many elements in the heap? | |
T | RemoveFirst () |
Take top/largest element off. | |
T | RemoveN (int i) |
Remove element from the middle. | |
void | AddElement (const T &elem) |
Put in heap and recompute to restore heap property. | |
void | AddElementDontHeapify (const T &elem) |
Put in heap but do NOT recompute to restore heap property. | |
void | Heapify () |
Recompute to restore heap property. | |
T & | First () |
Get reference to top of heap (do not remove). | |
T & | Value (int i) |
Get reference arbitrary element (do not remove). | |
const T & | Second () const |
Get reference element just below top (do not remove). | |
void | ReplacedFirst () |
Inform heap that I replaced the top: recompute, but more efficient than Heapify(). | |
void | IncreasedN (int i) |
Inform heap that element i must rise in heap to restore heap property. More efficient than general Heapify(). | |
void | DecreasedN (int i) |
Inform heap that element i must drop in heap to restore heap property. More efficient than general Heapify(). | |
void | CheckHeap () const |
Check heap property. | |
void | Print (ostream &out) const |
Dump heap. | |
bool | HeapProperty (int root) const |
Check heap property from given root to the bottom. | |
Protected Member Functions | |
int | LeftChild (int i) const |
int | RightChild (int i) const |
int | RightSibling (int i) const |
int | Parent (int i) const |
void | PrintRoot (ostream &out, int rootElem, int indentLevel) const |
void | CheckHeapRoot (int rootElem) const |
bool | HeapProperty (int lower, int upper) const |
void | SiftDown (int rootElem) |
void | SiftUp (int rootElem) |
void | GrowElements (int newSize) |
Protected Attributes | |
int | numElements |
int | maxNumElements |
T * | elements |
const Cmp & | cmp |