blob: 5ff1a7365ae4224d4ce6b1ef28b4322acf5e6918 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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;
}
|