00001 /*
00002 File: Heap.cc
00003
00004 Function:
00005
00006 Author: Andrew Willmott
00007
00008 Notes:
00009 */
00010
00011 #include "cl/Heap.h"
00012
00013
00014 HeapEntry *Heap::RemoveMax()
00015 {
00016 HeapEntry *result;
00017
00018 if (heap.NumItems() == 0)
00019 return(0);
00020
00021 result = heap[0];
00022 result->heapIdx = -1;
00023
00024 heap[0] = heap.Last();
00025 heap[0]->heapIdx = 0;
00026 heap.Shrink(1);
00027
00028 HeapifyDown(0);
00029
00030 return(result);
00031 }
00032
00033 Void Heap::Insert(HeapEntry *he)
00034 {
00035 heap.Append(he);
00036 he->heapIdx = heap.NumItems() - 1;
00037
00038 HeapifyUp(heap.NumItems() - 1);
00039 }
00040
00041 Void Heap::Delete(HeapEntry *he)
00042 {
00043 Assert(he->heapIdx >= 0, "Heap entry already deleted");
00044
00045 if (he->heapIdx < 0)
00046 return;
00047
00048 heap[he->heapIdx] = heap.Last();
00049 heap[he->heapIdx]->heapIdx = he->heapIdx;
00050 heap.Shrink(1);
00051
00052 HeapifyDown(he->heapIdx);
00053
00054 he->heapIdx = -1;
00055 }
00056
00057 Void Heap::Update(HeapEntry *he)
00058 {
00059 Int i = he->heapIdx;
00060
00061 Assert(i >= 0, "Can't update deleted entry");
00062
00063 if (i > 0 && heap[Parent(i)]->cost < he->cost)
00064 HeapifyUp(i);
00065 else
00066 HeapifyDown(i);
00067 }
00068
00069 Void Heap::HeapifyDown(Int i)
00070 {
00071 Int child, parent;
00072
00073 parent = i;
00074 child = Left(i);
00075
00076 while (child < heap.NumItems())
00077 {
00078 if (child + 1 < heap.NumItems() && heap[child]->cost < heap[child + 1]->cost)
00079 child++;
00080
00081 if (heap[child]->cost > heap[parent]->cost)
00082 {
00083 Swap(heap[child]->heapIdx, heap[parent]->heapIdx);
00084 Swap(heap[child], heap[parent]);
00085
00086 parent = child;
00087 child = Left(parent);
00088 }
00089 else
00090 break;
00091 }
00092 }
00093
00094 Void Heap::HeapifyUp(Int i)
00095 {
00096 Int child, parent;
00097
00098 child = i;
00099 parent = Parent(child);
00100
00101 while (parent >= 0)
00102 {
00103 if (heap[parent]->cost < heap[child]->cost)
00104 {
00105 Swap(heap[child]->heapIdx, heap[parent]->heapIdx);
00106 Swap(heap[child], heap[parent]);
00107 child = parent;
00108 parent = Parent(child);
00109 }
00110 else
00111 break;
00112 }
00113 }