#include "priority-queue.h" #include "da.h" static inline void swap(PRIORITY_QUEUE_ITEM a, PRIORITY_QUEUE_ITEM b) { struct priority_queue_item temp = *a; *a = *b; *b = temp; } static inline void heapify(PRIORITY_QUEUE pq, int idx) { int largest = 1*idx + 0; int left = 2*idx + 1; int right = 2*idx + 2; if (left < pq->count && pq->items[left ].priority < pq->items[largest].priority) largest = left; if (right < pq->count && pq->items[right].priority < pq->items[largest].priority) largest = right; if (largest != idx) { swap(&pq->items[idx], &pq->items[largest]); heapify(pq, largest); } } void priority_queue_push(PRIORITY_QUEUE pq, struct priority_queue_item item) { if (pq->count == pq->capacity) DA_ENSURE_CAPACITY(*pq, 1); int idx = pq->count; pq->items[idx] = item; pq->count++; while (idx > 0 && pq->items[(idx - 1)/2].priority > pq->items[idx ].priority) { swap(&pq->items[(idx - 1)/2], &pq->items[idx]); idx = (idx - 1)/2; } } void *priority_queue_pop(PRIORITY_QUEUE pq) { if (pq->count == 0) return NULL; void *min = pq->items[0].data; pq->items[0] = pq->items[pq->count - 1]; pq->count--; heapify(pq, 0); return min; }