If you found this article on the web I suppose you already know what a Priority Queue is . Of course it’s an abstract data type, that acts exactly like a queue, but additionally all the elements have priorities associated with them . So when you want to remove something from the Priority Queue, you will pull the highest priority element first .

To get better performance, we’ll going to implement the Priority Queue using a heap . Please follow the code comments:

pqueue.h

pqueue.c

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

test.h

test.c

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 on “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.

    Reply
  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.

    Reply
  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

    Reply

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url=""> 

required

Are we human, or are we dancer *