48 #define IN_PRIORITY_QUEUE
49 #include "priorityq-heap.c"
50 #undef IN_PRIORITY_QUEUE
55 #include "priorityq-sort.h"
58 PriorityQ *pqNewPriorityQ(
int (*leq)(PQkey key1, PQkey key2) )
61 if (pq == NULL)
return NULL;
63 pq->heap = __gl_pqHeapNewPriorityQ( leq );
64 if (pq->heap == NULL) {
69 pq->keys = (PQHeapKey *)memAlloc( INIT_SIZE *
sizeof(pq->keys[0]) );
70 if (pq->keys == NULL) {
71 __gl_pqHeapDeletePriorityQ(pq->heap);
78 pq->initialized = FALSE;
87 if (pq->heap != NULL) __gl_pqHeapDeletePriorityQ( pq->heap );
88 if (pq->order != NULL) memFree( pq->order );
89 if (pq->keys != NULL) memFree( pq->keys );
94 #define LT(x,y) (! LEQ(y,x))
95 #define GT(x,y) (! LEQ(x,y))
96 #define Swap(a,b) if(1){PQkey *tmp = *a; *a = *b; *b = tmp;}else
101 PQkey **p, **r, **i, **j, *piv;
102 struct { PQkey **p, **r; }
Stack[50], *top =
Stack;
103 unsigned long seed = 2016473283;
112 pq->order = (PQHeapKey **)memAlloc( (
size_t)
113 ((pq->size+1) *
sizeof(pq->order[0])) );
118 if (pq->order == NULL)
return 0;
121 r = p + pq->size - 1;
122 for( piv = pq->keys, i = p; i <= r; ++piv, ++i ) {
129 top->p = p; top->r = r; ++top;
130 while( --top >=
Stack ) {
133 while( r > p + 10 ) {
134 seed = seed * 1539415821 + 1;
135 i = p + seed % (r - p + 1);
142 do { ++i; }
while( GT( **i, *piv ));
143 do { --j; }
while( LT( **j, *piv ));
147 if( i - p < r - j ) {
148 top->p = j+1; top->r = r; ++top;
151 top->p = p; top->r = i-1; ++top;
156 for( i = p+1; i <= r; ++i ) {
158 for( j = i; j > p && LT( **(j-1), *piv ); --j ) {
165 pq->initialized = TRUE;
166 __gl_pqHeapInit( pq->heap );
170 r = p + pq->size - 1;
171 for( i = p; i < r; ++i ) {
172 assert( LEQ( **(i+1), **i ));
181 PQhandle pqInsert(
PriorityQ *pq, PQkey keyNew )
185 if( pq->initialized ) {
186 return __gl_pqHeapInsert( pq->heap, keyNew );
189 if( ++ pq->size >= pq->max ) {
190 PQkey *saveKey= pq->keys;
194 pq->keys = (PQHeapKey *)memRealloc( pq->keys,
196 (pq->max *
sizeof( pq->keys[0] )));
197 if (pq->keys == NULL) {
202 assert(curr != LONG_MAX);
203 pq->keys[curr] = keyNew;
212 PQkey sortMin, heapMin;
214 if( pq->size == 0 ) {
215 return __gl_pqHeapExtractMin( pq->heap );
217 sortMin = *(pq->order[pq->size-1]);
218 if( ! __gl_pqHeapIsEmpty( pq->heap )) {
219 heapMin = __gl_pqHeapMinimum( pq->heap );
220 if( LEQ( heapMin, sortMin )) {
221 return __gl_pqHeapExtractMin( pq->heap );
226 }
while( pq->size > 0 && *(pq->order[pq->size-1]) == NULL );
233 PQkey sortMin, heapMin;
235 if( pq->size == 0 ) {
236 return __gl_pqHeapMinimum( pq->heap );
238 sortMin = *(pq->order[pq->size-1]);
239 if( ! __gl_pqHeapIsEmpty( pq->heap )) {
240 heapMin = __gl_pqHeapMinimum( pq->heap );
241 if( LEQ( heapMin, sortMin )) {
251 return (pq->size == 0) && __gl_pqHeapIsEmpty( pq->heap );
255 void pqDelete(
PriorityQ *pq, PQhandle curr )
258 __gl_pqHeapDelete( pq->heap, curr );
262 assert( curr < pq->max && pq->keys[curr] != NULL );
264 pq->keys[curr] = NULL;
265 while( pq->size > 0 && *(pq->order[pq->size-1]) == NULL ) {