Implementing a min-heap in C

Why ?

When faced with the problem of implementing dijkstra’s and prim’s algorithm for my data structure class this year, I decided to implement it with a priority queue and that was designed as min-heap.

I tried to make the program as much modular as I could, hence I implemented the heap as header file.

The Code

typedef struct {
    int size, len;
    int *data, *index, *prio;
} heap;

heap *create_minheap(int size) {
    heap *h = (heap *)calloc(1, sizeof(heap));
    h->len = size;
    h->size = 0;
    h->index = (int *)calloc(size, sizeof(int));
    h->data = (int *)calloc(size + 1, sizeof(int));
    h->prio = (int *)calloc(size + 1, sizeof(int));
    return h;
}

void push_heap(heap *h, int v, int p) {
    int i = h->index[v] == 0 ? ++h->len : h->index[v];
    int j = i / 2;
    while (i > 1) {
        if (h->prio[j] < p)
            break;
        h->data[i] = h->data[j];
        h->prio[i] = h->prio[j];
        h->index[h->data[i]] = i;
        i = j;
        j = j / 2;
    }
    h->data[i] = v;
    h->prio[i] = p;
    h->index[v] = i;
}

int min(heap *h, int i, int j, int k) {
    int m = i;
    if (j <= h->len && h->prio[j] < h->prio[m])
        m = j;
    if (k <= h->len && h->prio[j] < h->prio[m])
        m = k;
    return m;
}

int pop_heap(heap *h) {
    int v = h->data[1];
    int i = 1;
    while (1) {
        int j = min(h, h->len, 2 * i, 2 * i + 1);
        if (j == h->len)
            break;
        h->data[i] = h->data[j];
        h->prio[i] = h->prio[j];
        h->index[h->data[i]] = i;
        i = j;
    }
    h->data[i] = h->data[h->len];
    h->prio[i] = h->prio[h->len];
    h->index[h->data[i]] = i;
    h->len--;
    return v;
}

back to the blog