CS302 Lecture Notes - Implementing a priority queue with an array-based binary heap


These lecture notes are very sketchy. You can get good information on Priority Queues from Wikipedia's Priority Queue Page and Binary Heap Page.

In this page we provide two implementations. In each, the heap is storing doubles. The first, in heap.cpp performs a simple implementation whose only inefficiency is that it implements creating a heap from a vector by simply calling push() on every one of the vector's elements.

The second, in heap2.cpp, implements the heap constructor method by putting elements from the back of the vector to the front, and calling Percolate_Down() on each element that has children. As we showed in class, that is a linear time operation, unlike the n log(n) implementation in heap.cpp.

Does it really make a difference? Well, I timed them both on my MacBook, and here are my results:

The difference is slight at best, and underscores a common feature of computer science research -- the theoretical does not match the actual! I don't have time to analyze it, but there's some effect that is going on as n doubles that could have to do with cache behavior, or some artifact of implementation. Suffice it to say that the two are awfully close!

There are two programs in this directory -- htest.cpp uses the heap to sort standard input, and hspeedtest.cpp tests the speed of creating and destroying a heap. There's also a makefile that makes two different sets of executables.