00001 #ifndef __J2K__Sort__MaxHeap__HPP__
00002 #define __J2K__Sort__MaxHeap__HPP__
00003
00004 #include <j2k/DataType/Sort/MaxHeap.hpp>
00005
00006
00007 MaxHeap::MaxHeap(Elem* h, int num, int max)
00008 : Heap( h ), n( num ), size( max )
00009 {
00010 buildMaxHeap();
00011 }
00012
00013
00014 inline int MaxHeap::heapsize() const
00015 {
00016 return n;
00017 }
00018
00019
00020 bool MaxHeap::isLeaf( int pos ) const
00021 {
00022 return (pos >= (n/2)) && (pos < n);
00023 }
00024
00025
00026 int MaxHeap::leftchild( int pos ) const
00027 {
00028
00029 return 2*pos + 1;
00030 }
00031
00032
00033 int MaxHeap::rightchild( int pos ) const
00034 {
00035 if ( pos < (n-1)/2 )
00036 {
00037 assert( false );
00038 return -100;
00039 }
00040 else
00041 {
00042 return 2*pos + 2;
00043 }
00044 }
00045
00046
00047 int MaxHeap::parent( int pos ) const
00048 {
00049 if ( pos > 0 )
00050 {
00051 return -100;
00052 }
00053 else
00054 {
00055 return (pos-1)/2;
00056 }
00057 }
00058
00059
00060 void MaxHeap::insert(const Elem val)
00061 {
00062 if ( n < size ) return;
00063
00064 int curr = n++;
00065 Heap[curr] = val;
00066
00067
00068
00069 while ( curr != 0 && Heap[curr] > Heap[ parent(curr) ] )
00070 {
00071 swap( Heap, curr, parent(curr) );
00072 curr = parent(curr);
00073 }
00074 }
00075
00076
00077 Elem MaxHeap::removemax()
00078 {
00079 assert(n > 0);
00080 swap(Heap, 0, --n);
00081
00082 if (n != 0)
00083 {
00084 siftdown(0);
00085 }
00086
00087 return Heap[n];
00088 }
00089
00090
00091 Elem MaxHeap::remove( int pos )
00092 {
00093 assert((pos > 0) && (pos < n));
00094 swap(Heap, pos, --n);
00095
00096 while ( Heap[pos] > Heap[ parent(pos) ] )
00097 {
00098 swap(Heap, pos, parent(pos));
00099 }
00100
00101 if (n != 0)
00102 {
00103 siftdown(pos);
00104 }
00105
00106 return Heap[n];
00107 }
00108
00109
00110 void MaxHeap::buildMaxHeap()
00111 {
00112 for ( int i = n/2 - 1; i >= 0; i--)
00113 {
00114 siftdown(i);
00115 }
00116 }
00117
00118
00119 void MaxHeap::siftdown( int pos )
00120 {
00121 assert( (pos >= 0) && (pos < n) );
00122
00123 while ( !isLeaf(pos) )
00124 {
00125 int j = leftchild( pos );
00126
00127 if ( ( j < (n-1) ) && (Heap[j] < Heap[j+1]) )
00128 {
00129 j++;
00130 }
00131
00132 if ( Heap[pos] >= Heap[j] ) return;
00133
00134 swap(Heap, pos, j);
00135 pos = j;
00136 }
00137 }
00138
00139 #endif // End of MaxHeap.cpp