// File: Heap_ADT.cpp // Array Heap ADT implementation #include #include "Heap_ADT.h" template HeapADT::HeapADT() : eltsInHeap(0) {eltsInHeap=0;} // Get for printing template vector HeapADT::getData() const { return(heap);} template void HeapADT::insertToHeap(heapEltType elt) {//heap[eltsInHeap++]=elt; heap.push_back(elt); eltsInHeap++; if (eltsInHeap>1) reheapUp(); } template void HeapADT::removeFromHeap(heapEltType &elt) {elt=heap[0]; heap[0]=heap[--eltsInHeap]; // Keep heap fully used heap.pop_back(); reheapDown(); } template int HeapADT::isHeapEmpty() {return((eltsInHeap==0)); } template void HeapADT::reheapUp() {int eltIndex=eltsInHeap-1; while(eltIndex>0 && heap[eltIndex]>heap[parentOfNode(eltIndex)]) { swap(heap[eltIndex],heap[parentOfNode(eltIndex)]); eltIndex=parentOfNode(eltIndex); } } template void HeapADT::reheapDown() {int eltIndex=0,MaxIndex,Done=0; do { MaxIndex=maxChild(eltIndex); if (MaxIndex>0 && heap[eltIndex] int HeapADT::parentOfNode(int Index) {if (Index>0) return((Index-1)/2); return(-1); } template int HeapADT::leftChild(int Index) const {if (Index*2+1 int HeapADT::rightChild(int Index) const {if (Index*2+2 int HeapADT::maxChild(int Index) {if (leftChild(Index)>0 && rightChild(Index)>0) { if (heap[leftChild(Index)]>heap[rightChild(Index)]) return(leftChild(Index)); return(rightChild(Index)); } if (leftChild(Index)>0) return(leftChild(Index)); if (rightChild(Index)>0) return(rightChild(Index)); return(-1); } template void HeapADT::swap(heapEltType &x,heapEltType &y) {heapEltType temp; temp=x; x=y; y=temp; } template ostream &operator << (ostream &out,const HeapADT &TheHeap) { vector TheHeapVector=TheHeap.getData(); typename vector::iterator it; for (it=TheHeapVector.begin(); it != TheHeapVector.end(); it++) out << *it << " "; out << endl; return(out); } template void HeapADT::heapPrint() const { // A queue to hold indices. An entry of -1 indicates end of level. queue nodeList; // Process Root if (heap.size()>0) { // print root cout << heap[0]; // and an end of level marker nodeList.push(0); // Insert its children nodeList.push(leftChild(0)); // left child nodeList.push(rightChild(0)); // right child } int index=nodeList.front(); while (index; template ostream &operator << (ostream &out,const HeapADT &TheHeap);