00001
00017 #include "Heap.h"
00018
00019 Heap::Heap() : size(0)
00020 {
00021 }
00022
00023 Heap::~Heap()
00024 {
00025 }
00026
00027 bool Heap::heapIsEmpty() const
00028 {
00029 return bool(size == 0);
00030 }
00031
00032 void Heap::heapInsert(const HeapItemType& newItem)
00033 throw(HeapException)
00034
00035
00036
00037 {
00038 if (size >= MAX_HEAP)
00039 throw HeapException("HeapException: Heap full");
00040
00041 items[size] = newItem;
00042
00043
00044 int place = size;
00045 int parent = (place - 1)/2;
00046 while ( (parent >= 0) &&
00047 (items[place].getKey() > items[parent].getKey()) )
00048 {
00049 HeapItemType temp = items[parent];
00050 items[parent] = items[place];
00051 items[place] = temp;
00052
00053 place = parent;
00054 parent = (place - 1)/2;
00055 }
00056
00057 ++size;
00058 }
00059
00060 void Heap::heapDelete(HeapItemType& rootItem)
00061 throw(HeapException)
00062
00063
00064 {
00065 if (heapIsEmpty())
00066 throw HeapException("HeapException: Heap empty");
00067 else
00068 { rootItem = items[0];
00069 items[0] = items[--size];
00070 heapRebuild(0);
00071 }
00072 }
00073
00074 void Heap::heapRebuild(int root)
00075 {
00076
00077
00078
00079 int child = 2 * root + 1;
00080
00081 if ( child < size )
00082 {
00083 int rightChild = child + 1;
00084
00085
00086
00087 if ( (rightChild < size) &&
00088 (items[rightChild].getKey() > items[child].getKey()) )
00089 child = rightChild;
00090
00091
00092
00093 if ( items[root].getKey() < items[child].getKey() )
00094 { HeapItemType temp = items[root];
00095 items[root] = items[child];
00096 items[child] = temp;
00097
00098
00099 heapRebuild(child);
00100 }
00101 }
00102
00103
00104 }
00105