diff options
| author | 2026-11-07 06:12:48 +0000 | |
|---|---|---|
| committer | 2026-11-07 06:21:22 +0000 | |
| commit | 39dcac2281970febcce36a0151796af2986388b3 (patch) | |
| tree | 7339e54dc942a3ab0d9ba9daae56a2801c1917e9 /src/priority-queue.c | |
| download | coursework-39dcac2281970febcce36a0151796af2986388b3.tar.gz | |
Diffstat (limited to 'src/priority-queue.c')
| -rw-r--r-- | src/priority-queue.c | 55 |
1 files changed, 55 insertions, 0 deletions
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 @@ | |||
| 1 | #include "priority-queue.h" | ||
| 2 | #include "da.h" | ||
| 3 | |||
| 4 | static inline void swap(PRIORITY_QUEUE_ITEM a, | ||
| 5 | PRIORITY_QUEUE_ITEM b) | ||
| 6 | { | ||
| 7 | struct priority_queue_item temp = *a; | ||
| 8 | *a = *b; | ||
| 9 | *b = temp; | ||
| 10 | } | ||
| 11 | |||
| 12 | static inline void heapify(PRIORITY_QUEUE pq, int idx) | ||
| 13 | { | ||
| 14 | int largest = 1*idx + 0; | ||
| 15 | int left = 2*idx + 1; | ||
| 16 | int right = 2*idx + 2; | ||
| 17 | |||
| 18 | if (left < pq->count && pq->items[left ].priority < pq->items[largest].priority) largest = left; | ||
| 19 | if (right < pq->count && pq->items[right].priority < pq->items[largest].priority) largest = right; | ||
| 20 | if (largest != idx) { | ||
| 21 | swap(&pq->items[idx], &pq->items[largest]); | ||
| 22 | heapify(pq, largest); | ||
| 23 | } | ||
| 24 | } | ||
| 25 | |||
| 26 | void priority_queue_push(PRIORITY_QUEUE pq, struct priority_queue_item item) | ||
| 27 | { | ||
| 28 | if (pq->count == pq->capacity) | ||
| 29 | DA_ENSURE_CAPACITY(*pq, 1); | ||
| 30 | |||
| 31 | int idx = pq->count; | ||
| 32 | pq->items[idx] = item; | ||
| 33 | pq->count++; | ||
| 34 | |||
| 35 | while (idx > 0 && | ||
| 36 | pq->items[(idx - 1)/2].priority > | ||
| 37 | pq->items[idx ].priority) { | ||
| 38 | swap(&pq->items[(idx - 1)/2], | ||
| 39 | &pq->items[idx]); | ||
| 40 | idx = (idx - 1)/2; | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | void *priority_queue_pop(PRIORITY_QUEUE pq) | ||
| 45 | { | ||
| 46 | if (pq->count == 0) | ||
| 47 | return NULL; | ||
| 48 | |||
| 49 | void *min = pq->items[0].data; | ||
| 50 | pq->items[0] = pq->items[pq->count - 1]; | ||
| 51 | pq->count--; | ||
| 52 | heapify(pq, 0); | ||
| 53 | |||
| 54 | return min; | ||
| 55 | } | ||
