Binary Heaps in C

After conducting a short search for a decent implementation of a binary heap in C I ended up having to write one. Some requirements were: no dependencies, no dynamically allocated memory, no need to modify the source to extend to new types.

The first result found from a google search yielded this OK implementation. Unfortunately it makes use of allocation routines and has a couple annoying header dependencies. It also defines the macro CMP, a fairly commonly used macro. The idea is a good idea — if we define a modifiable macro the heap can be converted to a min or max heap as needed. However in practice this is not that useful; if we use min heap first, and later require max heap, we then still need to copy + paste out a new set of heap source files. Why not just make the two different sources up-front once and for all? It also typedefs the internal type, so use of the header would require alteration of the header. This triggers recompiles, and is a pain to maintain as new types of data are needed, perhaps copy and pasting new implementations around, modifying the build system as necessary to accommodate the new files, etc.

This implementation suffers almost identical downsides, and has no way to store auxiliary data at all. Heaps of only single integers are not very useful!

One nice strategy is it uses a void* and stride size so the heap could hold arbitrary pieces of POD memory. A small downside to this strategy is the requirement to constantly multiply stride with indices, which sort of clutters the source. Not really a big deal, just a nit-pick. I actually could not find a single implementation that takes this strategy.

In the end I decided to use an indirection trick: sort an array of struct { int key, int val }, where the val member is used as an index into an array of auxiliary data. The key integer is used for sorting, and the val integer is used to lookup data associated with a key. This implementation style can be re-used for any kind of data without C++ templates, and without requiring the user to mess with the source, ever.

And here’s the output:

TwitterRedditFacebookShare

Leave a Reply

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