Implementing a generic Priority Queue in C (using heaps)

This article considers you are already familiar with the concept of a Priority Queue.

It’s a Queue with a twist. You push() elements like in a standard Queue, but when it comes to pop() them out you take the element with the “highest” priority.

The implementation is going to use a Binary Heap.

The following code is also available on github:



In order to test this “lovely” code we will write a bogus structure, and an allocator / de-allocator for it .



And the main function:

And the output:

Just as expected the random numbers that were being inserted are shown in the right order, decided by the comparator function .

8 thoughts to “Implementing a generic Priority Queue in C (using heaps)”

  1. Hi,

    You are missing
    res->capacity = capacity;

    in pqueue_new() function in pqueue.c

    Thanks for giving out the code.

  2. The way he has impleted the priority queue, x/1 for PARENT is completely valid. Probably you are confusion it with psuedo code that algorithms books have.

  3. I am unable to see which files you have included. The first few “#include” s are not complete. Can you please upload your code again if possible? Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

Are we human, or are we dancer *