From 39dcac2281970febcce36a0151796af2986388b3 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sat, 7 Nov 2026 09:12:48 +0300 Subject: publish --- src/priority-queue.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/priority-queue.c (limited to 'src/priority-queue.c') diff --git a/src/priority-queue.c b/src/priority-queue.c new file mode 100644 index 0000000..5ff1a73 --- /dev/null +++ b/src/priority-queue.c @@ -0,0 +1,55 @@ +#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; +} -- cgit v1.3.1