#ifndef HEAP_ARRAY_H_ #define HEAP_ARRAY_H_ #include"key_item.h" #include"heap_exception.h" typedef KeyItem HeapItemType; const int MAX_HEAP = 50; class Heap { public: Heap();//default constructor //copy constructor and destructor are //supplied by the complier //heap operations : virtual bool empty()const; //detemines whether a heap is empty //precondition :none; //postcondition :return true if the heap is empty; //otherwise return false virtual void heapInsert(const HeapItemType &newitem) throw(HeapException); //inserts a item into a heap //precondition :newitem is the item to be inserted //postcondition :If the heap is not full,newitem is in //its proper position ;otherwise HeapException is thrown virtual void heapDelete(HeapItemType & rootItem) throw(HeapException); //retrieve and delete the item in the root of //the heap .this item has the largest search key //in the heap //precondition :none //postcondition :if the heap is not empty ,rootitem is the //retrieved item ,the item is deleted from the heap . //however,if the item is empty.removal is //impossible and the function throws heap exception //void display()const; protected: void heapRebuild(int root); //converts the semiheap rooted at index root into //a heap private: HeapItemType items[MAX_HEAP]; int size; }; #endif
heap类的实现文件
#include"heap_array.h" #include<iostream> using namespace std; Heap::Heap():size(0) {} bool Heap::empty()const { return (size==0); } void Heap::heapInsert(const HeapItemType &newitem) throw(HeapException) { if(size>=MAX_HEAP) throw HeapException("HeapException:the heap is full !"); else { items[size]=newitem; int place=size; int parent=(place-1)/2; while((parent>=0)&&(items[place].getKey()>items[parent].getKey())) { HeapItemType temp=items[parent]; items[parent]=items[place]; items[place]=temp; place=parent; parent=(place-1)/2; } size++; } } /** void Heap::display()const { for(int i=0;i<size;i++) cout<<items[i].getKey()<<endl; } **/ void Heap::heapDelete(HeapItemType &rootItem) throw(HeapException) { if(empty()) throw HeapException("HeapException :the heap is empty !"); else { rootItem=items[0]; items[0]=items[size-1]; --size; heapRebuild(0); } } void Heap::heapRebuild(int root) { int child=2*root+1; if(child<=size-1) { int rightChild=child+1; if(rightChild<=size-1) if(items[child].getKey()<items[rightChild].getKey()) child=rightChild; //if the root's value is smaller than the value in the //larger child ,swap values if(items[root].getKey()<items[child].getKey()) { HeapItemType temp=items[root]; items[root]=items[child]; items[child]=temp; //transform the new subtree into a heap heapRebuild(child); } } }