MeshKit  1.0
Heap.cpp
Go to the documentation of this file.
00001 #include <iostream>
00002 #include "std.h"
00003 #include "Heap.hpp"
00004 #include <string.h> /* for memcpy */
00005 
00006 
00007 void Heap::swap(int i,int j)
00008 {
00009     heap_node tmp = ref(i);
00010 
00011     ref(i) = ref(j);
00012     ref(j) = tmp;
00013 
00014     ref(i).obj->setHeapPos(i);
00015     ref(j).obj->setHeapPos(j);
00016 }
00017 
00018 void Heap::upheap(int i)
00019 {
00020     if( i==0 ) return;
00021 
00022     if( ref(i).import > ref(parent(i)).import ) {
00023         swap(i,parent(i));
00024         upheap(parent(i));
00025     }
00026 }
00027 
00028 void Heap::downheap(int i)
00029 {
00030     if (i>=size) return;        // perhaps just extracted the last
00031 
00032     int largest = i,
00033         l = left(i),
00034         r = right(i);
00035 
00036     if( l<size && ref(l).import > ref(largest).import ) largest = l;
00037     if( r<size && ref(r).import > ref(largest).import ) largest = r;
00038 
00039     if( largest != i ) {
00040         swap(i,largest);
00041         downheap(largest);
00042     }
00043 }
00044 
00045 
00046 
00047 void Heap::insert(Heapable *t,double v)
00048 {
00049     if( size == maxLength() )
00050     {
00051         std::cerr << "NOTE: Growing heap from " << size << " to " << 2*size << std::endl;
00052         resize(2*size);
00053     }
00054 
00055     int i = size++;
00056 
00057     ref(i).obj = t;
00058     ref(i).import = v;
00059 
00060     ref(i).obj->setHeapPos(i);
00061 
00062     upheap(i);
00063 }
00064 
00065 void Heap::update(Heapable *t,double v)
00066 {
00067     int i = t->getHeapPos();
00068 
00069     if( i >= size )
00070     {
00071         std::cerr << "WARNING: Attempting to update past end of heap!" << std::endl;
00072         return;
00073     }
00074     else if( i == NOT_IN_HEAP )
00075     {
00076         std::cerr << "WARNING: Attempting to update object not in heap!" << std::endl;
00077         return;
00078     }
00079 
00080     float old=ref(i).import;
00081     ref(i).import = v;
00082 
00083     if( v<old )
00084         downheap(i);
00085     else
00086         upheap(i);
00087 }
00088 
00089 
00090 
00091 heap_node *Heap::extract()
00092 {
00093     if( size<1 ) return 0;
00094 
00095     swap(0,size-1);
00096     size--;
00097 
00098     downheap(0);
00099 
00100     ref(size).obj->notInHeap();
00101 
00102     return &ref(size);
00103 }
00104 
00105 heap_node *Heap::kill(int i)
00106 {
00107     if( i>=size )
00108         std::cerr << "WARNING: Attempt to delete invalid heap node." << std::endl;
00109 
00110     swap(i, size-1);
00111     size--;
00112     ref(size).obj->notInHeap();
00113 
00114     if( ref(i).import < ref(size).import )
00115         downheap(i);
00116     else
00117         upheap(i);
00118 
00119 
00120     return &ref(size);
00121 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines