39 #ifdef IN_PRIORITY_QUEUE
43 #include "priorityq-heap.h"
53 #ifdef FOR_TRITE_TEST_PROGRAM
54 #define LEQ(x,y) (*pq->leq)(x,y)
58 #define LEQ(x,y) VertLeq((GLUvertex *)x, (GLUvertex *)y)
62 PriorityQ *pqNewPriorityQ(
int (*leq)(PQkey key1, PQkey key2) )
65 if (pq == NULL)
return NULL;
69 pq->nodes = (
PQnode *)memAlloc( (INIT_SIZE + 1) *
sizeof(pq->nodes[0]) );
70 if (pq->nodes == NULL) {
75 pq->handles = (
PQhandleElem *)memAlloc( (INIT_SIZE + 1) *
sizeof(pq->handles[0]) );
76 if (pq->handles == NULL) {
82 pq->initialized = FALSE;
86 pq->nodes[1].handle = 1;
87 pq->handles[1].key = NULL;
94 memFree( pq->handles );
100 static void FloatDown(
PriorityQ *pq,
long curr )
104 PQhandle hCurr, hChild;
107 hCurr = n[curr].handle;
110 if( child < pq->size && LEQ( h[n[child+1].handle].
key,
111 h[n[child].handle].key )) {
115 assert(child <= pq->max);
117 hChild = n[child].handle;
118 if( child > pq->size || LEQ( h[hCurr].key, h[hChild].key )) {
119 n[curr].handle = hCurr;
120 h[hCurr].node = curr;
123 n[curr].handle = hChild;
124 h[hChild].node = curr;
130 static void FloatUp(
PriorityQ *pq,
long curr )
134 PQhandle hCurr, hParent;
137 hCurr = n[curr].handle;
140 hParent = n[parent].handle;
141 if( parent == 0 || LEQ( h[hParent].key, h[hCurr].key )) {
142 n[curr].handle = hCurr;
143 h[hCurr].node = curr;
146 n[curr].handle = hParent;
147 h[hParent].node = curr;
159 for( i = pq->size; i >= 1; --i ) {
162 pq->initialized = TRUE;
167 PQhandle pqInsert(
PriorityQ *pq, PQkey keyNew )
173 if( (curr*2) > pq->max ) {
174 PQnode *saveNodes= pq->nodes;
179 pq->nodes = (
PQnode *)memRealloc( pq->nodes,
181 ((pq->max + 1) *
sizeof( pq->nodes[0] )));
182 if (pq->nodes == NULL) {
183 pq->nodes = saveNodes;
189 sizeof( pq->handles[0] )));
190 if (pq->handles == NULL) {
191 pq->handles = saveHandles;
196 if( pq->freeList == 0 ) {
200 pq->freeList = pq->handles[free].node;
203 pq->nodes[curr].handle = free;
204 pq->handles[free].node = curr;
205 pq->handles[free].key = keyNew;
207 if( pq->initialized ) {
210 assert(free != LONG_MAX);
219 PQhandle hMin = n[1].handle;
220 PQkey min = h[hMin].key;
223 n[1].handle = n[pq->size].handle;
224 h[n[1].handle].node = 1;
227 h[hMin].node = pq->freeList;
230 if( -- pq->size > 0 ) {
238 void pqDelete(
PriorityQ *pq, PQhandle hCurr )
244 assert( hCurr >= 1 && hCurr <= pq->max && h[hCurr].key != NULL );
246 curr = h[hCurr].node;
247 n[curr].handle = n[pq->size].handle;
248 h[n[curr].handle].node = curr;
250 if( curr <= -- pq->size ) {
251 if( curr <= 1 || LEQ( h[n[curr>>1].handle].key, h[n[curr].handle].key )) {
252 FloatDown( pq, curr );
258 h[hCurr].node = pq->freeList;
259 pq->freeList = hCurr;
262 #endif //IN_PRIORITY_QUEUE