* @brief Priority Queue implementation based on the heap datastructure
* @version $Id$
*/
+#include "config.h"
+
#include "array.h"
#include "pqueue.h"
+#include "error.h"
/*
* Implements a heap.
*
*/
-typedef struct _pqueue_el_t {
+typedef struct pqueue_el_t {
void *data;
- int key;
+ int priority;
} pqueue_el_t;
-struct _pqueue_t {
+struct pqueue_t {
pqueue_el_t *elems;
};
* Enforces the heap characteristics if the queue
* starting from element at position @p pos.
*/
-static void pqueue_heapify(pqueue_t *q, unsigned pos) {
+static void pqueue_heapify(pqueue_t *q, unsigned pos)
+{
unsigned len = ARR_LEN(q->elems);
while (pos * 2 < len) {
pqueue_el_t tmp;
unsigned exchange = pos;
- if (q->elems[exchange].key < q->elems[pos * 2].key) {
+ if (q->elems[exchange].priority < q->elems[pos * 2].priority) {
exchange = pos * 2;
}
- if ((pos * 2 + 1) < len && q->elems[exchange].key < q->elems[pos * 2 + 1].key) {
+ if ((pos * 2 + 1) < len
+ && q->elems[exchange].priority < q->elems[pos * 2 + 1].priority) {
exchange = pos * 2 + 1;
}
/**
* Sifts up a newly inserted element at position @p pos.
*/
-static void pqueue_sift_up(pqueue_t *q, unsigned pos) {
- while(q->elems[pos].key > q->elems[pos / 2].key) {
+static void pqueue_sift_up(pqueue_t *q, unsigned pos)
+{
+ while (q->elems[pos].priority > q->elems[pos / 2].priority) {
pqueue_el_t tmp;
tmp = q->elems[pos];
}
}
-pqueue_t *new_pqueue(void) {
- pqueue_t *res = xmalloc(sizeof(*res));
+pqueue_t *new_pqueue(void)
+{
+ pqueue_t *res = XMALLOC(pqueue_t);
res->elems = NEW_ARR_F(pqueue_el_t, 0);
return res;
}
-void del_pqueue(pqueue_t *q) {
+void del_pqueue(pqueue_t *q)
+{
DEL_ARR_F(q->elems);
free(q);
}
-void pqueue_put(pqueue_t *q, void *data, int key) {
+void pqueue_put(pqueue_t *q, void *data, int priority)
+{
pqueue_el_t el;
- el.data = data;
- el.key = key;
+ el.data = data;
+ el.priority = priority;
ARR_APP1(pqueue_el_t, q->elems, el);
pqueue_sift_up(q, ARR_LEN(q->elems) - 1);
}
-void *pqueue_pop_front(pqueue_t *q) {
- switch(ARR_LEN(q->elems)) {
+void *pqueue_pop_front(pqueue_t *q)
+{
+ switch (ARR_LEN(q->elems)) {
case 0:
- assert(0 && "Attempt to retrieve element from empty priority queue.");
- return NULL;
- break;
+ panic("Attempt to retrieve element from empty priority queue.");
case 1:
ARR_SHRINKLEN(q->elems, 0);
return q->elems[0].data;
- break;
default: {
void *data = q->elems[0].data;
int len = ARR_LEN(q->elems) - 1;
}
}
-int pqueue_length(const pqueue_t *q) {
+int pqueue_length(const pqueue_t *q)
+{
return ARR_LEN(q->elems);
}
-int pqueue_empty(const pqueue_t *q) {
+int pqueue_empty(const pqueue_t *q)
+{
return ARR_LEN(q->elems) == 0;
}