#include "tpqueue.h" template PQueue::PQueue(int n) : myList(n+1), myNumElts(0) // postcondition: all fields initialized, priority queue has room // for n elements { } template PQueue::~PQueue() // postcondition: priority queue is "garbage" { myNumElts = 0; } template int PQueue::NumElts() const // postcondition: returns number of items queued up { return myNumElts; } template bool PQueue::IsEmpty() const // postcondition: returns true if pqueue is empty, else false { return myNumElts == 0; } template void PQueue::Insert(const Kind & elt, int prio) { if (myNumElts >= myList.Length()-1) { myList.SetSize(myList.Length() * 2); // grow if necessary } myNumElts++; // add at end (heap shape) int k = myNumElts; // location of new element while (k > 1 && myList[k/2].priority > prio) { myList[k] = myList[k/2]; k /= 2; } myList[k].thing = elt; myList[k].priority = prio; } template void PQueue::DeleteMin() // precondition: ! IsEmpty() // postcondition: remove minimal element from priority queue { if (! IsEmpty()) { myList[1] = myList[myNumElts]; // move last to top myNumElts--; Heapify(1); // and push down } } template void PQueue::MinElt(Kind & ref,int & prio) // postcondition: set ref/prio to minimum element in heap { ref = myList[1].thing; prio = myList[1].priority; } template void PQueue::Heapify(int vroot) // preconditon: subheaps of vroot satisfy heap property (and shape) // postcondition: heap rooted at vroot satisfies heap property { Qelt 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 && myList[child].priority > myList[child+1].priority) { child++; } if (last.priority <= myList[child].priority) // it goes here { break; } else { myList[k] = myList[child]; k = child; } } // found "resting place", insert 'last element' myList[k] = last; }