00001 #ifndef DEF_HEAP
00002 #define DEF_HEAP
00003
00004
00005
00006
00007
00008 namespace groupindex
00009 {
00010
00011 template<class ItemClass>
00012 void trickle(ItemClass** heap, int i, int m)
00013
00014 {
00015 ItemClass* t;
00016 int j;
00017
00018 while (2*i <= m)
00019 {
00020
00021 j = 2*i;
00022
00023 if (j<m)
00024 if (*heap[j-1] > *heap[j])
00025 j++;
00026
00027 if (*heap[i-1] > *heap[j-1])
00028 {
00029
00030
00031 t = heap[i-1]; heap[i-1] = heap[j-1]; heap[j-1] = t;
00032
00033
00034 i = j;
00035 } else {
00036
00037 i = m;
00038
00039 }
00040
00041 }
00042 };
00043
00044 template<class ItemClass>
00045 void heapify(ItemClass** heap, int length)
00046
00047
00048 {
00049
00050 for (int i=(length+1)/2; i>0; i--)
00051 {
00052 trickle<ItemClass>(heap, i, length);
00053 }
00054 };
00055
00056
00057 template<class ItemClass>
00058 void heapsort(ItemClass** heap, int length)
00059 {
00060 heapify<ItemClass>(heap, length);
00061
00062 for (int i=length-1; i>0; i--)
00063 {
00064 ItemClass* t = heap[i];
00065 heap[i] = heap[0];
00066 heap[0] = t;
00067 trickle<ItemClass>(heap, 1, i);
00068 }
00069 };
00070
00071
00072
00073 template<class HeapClass>
00074 HeapClass* removeTopFromHeap(HeapClass** heap, int& length)
00075
00076
00077
00078
00079
00080 {
00081 HeapClass* first = heap[0];
00082 heap[0] = heap[length-1];
00083 heap[length-1] = first;
00084
00085 length--;
00086
00087 trickle<HeapClass>(heap, 1, length);
00088
00089 return first;
00090 };
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104
00105
00106 template<class ItemClass>
00107 void trickle(ItemClass* heap, int i, int m)
00108
00109 {
00110 ItemClass t;
00111 int j;
00112
00113 while (2*i <= m)
00114 {
00115
00116 j = 2*i;
00117
00118 if (j<m)
00119 if (heap[j-1] > heap[j])
00120 j++;
00121
00122 if (heap[i-1] > heap[j-1])
00123 {
00124
00125
00126 t = heap[i-1]; heap[i-1] = heap[j-1]; heap[j-1] = t;
00127
00128
00129 i = j;
00130 } else {
00131
00132 i = m;
00133
00134 }
00135
00136 }
00137 };
00138
00139 template<class ItemClass>
00140 void heapify(ItemClass* heap, int length)
00141
00142
00143 {
00144
00145 for (int i=(length+1)/2; i>0; i--)
00146 {
00147 trickle(heap, i, length);
00148 }
00149 };
00150
00151
00152 template<class ItemClass>
00153 void heapsort(ItemClass* heap, int length)
00154 {
00155 heapify(heap, length);
00156
00157 for (int i=length-1; i>0; i--)
00158 {
00159 ItemClass t = heap[i];
00160 heap[i] = heap[0];
00161 heap[0] = t;
00162 trickle(heap, 1, i);
00163 }
00164 };
00165
00166
00167
00168 template<class HeapClass>
00169 HeapClass removeTopFromHeap(HeapClass* heap, int& length)
00170
00171
00172
00173
00174
00175 {
00176 HeapClass first = heap[0];
00177 heap[0] = heap[length-1];
00178 heap[length-1] = first;
00179
00180 length--;
00181
00182 trickle(heap, 1, length);
00183
00184 return first;
00185 };
00186
00187 }
00188
00189 #endif