#include using namespace std; static int DEFAULT = 11; // initial size, file scope variable template Comparer tpqueue::ourComp = Comparer(); template tpqueue::tpqueue() : myComp(ourComp), myNumElts(0) { init(DEFAULT); } template tpqueue::tpqueue(const Comparer& cmp) : myComp(cmp), myNumElts(0) // postcondition: all fields initialized, priority queue has room // for ten elements { init(DEFAULT); } template void tpqueue::init(int n) // postcondition: list reserves space for n elements // myList[0] contains garbage heap starts at myList[1] { myList.reserve(n); myList.push_back(Kind()); } template tpqueue::~tpqueue() // postcondition: priority queue is "garbage" { } template int tpqueue::size() const // postcondition: returns number of items queued up { return myNumElts; } template bool tpqueue::isEmpty() const // postcondition: returns true if pqueue is empty, else false { return myNumElts == 0; } template void tpqueue::insert(const Kind & elt) { myList.push_back(elt); // increase size of heap myNumElts++; // add at end (heap shape) int k = myNumElts; // location of new element while (k > 1 && myComp.compare(myList[k/2],elt) > 0) { myList[k] = myList[k/2]; k /= 2; } myList[k] = elt; } template void tpqueue::deletemin() // precondition: ! isEmpty() // postcondition: remove minimal element from priority queue { if (! isEmpty()) { myList[1] = myList[myNumElts]; // move last to top myList.pop_back(); // reduce size of heap myNumElts--; if (myNumElts > 1) heapify(1); // and push down } } template void tpqueue::deletemin(Kind & ref) // precondition: ! isEmpty() // postcondition: remove minimal element from priority queue // set ref/prio to minimum element in heap { if (! isEmpty()) { ref = getmin(); deletemin(); } } template void tpqueue::dump() const { cout << size() << "\t"; for(int k=1; k <= size(); k++) { cout << myList[k] << " "; } cout << endl; } template Kind& tpqueue::getmin() // postcondition: set ref/prio to minimum element in heap { return myList[1]; } template void tpqueue::heapify(int vroot) // preconditon: subheaps of vroot satisfy heap property (and shape) // postcondition: heap rooted at vroot satisfies heap property { Kind last = myList[vroot]; int child, k = vroot; while (2*k <= myNumElts) { // find minimal child (assume left, then check right) child = 2*k; if (child < myNumElts && myComp.compare(myList[child], myList[child+1]) > 0) { child++; } if (myComp.compare(last, myList[child]) <=0) // it goes here { break; } else { myList[k] = myList[child]; k = child; } } // found "resting place", insert 'last element' myList[k] = last; }