Heaps and Priority Queues in ds 1.31

I recently revised and improved the Heap and PriorityQueue classes, mainly because the difference between both has always been somewhat blurry. The new implementations are included in ds 1.31, so let’s talk a bit about the changes.

The Heap class

By definition, a heap is a dense binary tree for which every parent node has a value that is less (or greater; henceforward I assume elements are sorted in ascending order) than or equal to any of its children. A heap defines a set of simple operations:

  • Insert element
  • Query smallest element
  • Remove smallest element

In the old implementation, insertion was done by calling enqueue(), and removal by calling dequeue(). This was a bit misleading because a heap is not a queue, instead it’s used as an efficient data structure for implementing priority queues. Thus the existing heap API has been modified and now consists of the methods add(), top() and pop(), corresponding to the old methods enqueue(), front() and dequeue(), respectively. I’ve also added some additional methods:

  • replace() – replaces the smallest element with a new element
  • change() – updates an existing element after it has been changed (restores heap condition)
  • sort() – returns a sorted array of all elements (runs the heap sort algorithm)
  • bottom() – finds and returns the largest element
  • repair() – rebuilds the entire heap

Note that replace() and change() is a lot faster than a combined remove() and add() operation. Also, bottom() runs in O(n) wheres top() is O(1). This can be further improved by a Min-Max Heap, which I may add in a future release.

Last but not least I did some optimizations, lowering memory requirements and almost doubling performance. And you don’t have to enable element-removal capabilities through the constructor as the heap now always supports removal of arbitrary elements.

The PriorityQueue class

As mentioned above, heaps are used for implementing priority queues and as the name implies, it’s a queue ADT so PriorityQueue now implements the Queue interface, defining the following methods:

  • enqueue() – adds an element
  • dequeue() – removes the element with the highest priority
  • peek() – returns the element with the highest priority (without removing it)
  • back() – returns the element with the lowest priority (without removing it)

The Heap class requires that every element provides a comparison function by implementing the Heapable interface. This is not needed for the PriorityQueue class, because here the elements are sorted using integer keys, resulting in a much better performance. So if you are only interested in managing prioritized data this is the perfect choice, while the Heap class is best used as an all-round tool for solving common problems like finding the min, max or k-th largest element.

Usage

Elements to be inserted into a heap have to implement the Heapable interface, which is defined in haXe like so:

interface Heapable implements Comparable
{
    /**
     * Tracks the position inside a binary heap.
     * This value should never be changed by the user.
     */
    var position:Int;
}

Declaring a field in an interface is not supported in ActionScript 3.0, so when you inspect the compiled class from an SWC file, it has become an empty marker interface. So don’t forget to define the position field as you don’t get compile-time errors. I could have defined position as a getter/setter style function, but I don’t want to give up all those nice haXe features because it has become my primary language for a long time now. So the AS3 implementation of a heap element would look like this:

package
{
    import de.polygonal.ds.Heapable;
    
    class HeapElement implements Heapable
    {
        public var value:int;
        public var position:int;

        public function HeapElement(value:int)
        {
            this.value = value;
        }

        public function compare(other:Object):int
        {
            return other.value - value;
        }

        public function toString():String
        {
            return "" + value;
        }
    }
}

Similary, elements to be inserted into a PriorityQueue have to implement Prioritizable like this:

package
{
    import de.polygonal.ds.Prioritizable;
    
    class PriorityQueueElement implements Prioritizable
    {
        public var priority:Int;
        public var position:Int;
        public function PriorityQueueElement() {}
    }
}

Once we have a heap element defined, we can use the Heap like so:

...
var heap = new Heap();
var a:HeapElement = new HeapElement(2);
var b:HeapElement = new HeapElement(5);
var c:HeapElement = new HeapElement(9);

//insert elements
heap.add(a);
heap.add(b);
heap.add(c);

//dump all elements
trace(heap);

//query smallest element
trace(heap.top());

//change element
a.value += 4;
heap.change(a);

//remove smallest element
trace(heap.pop());

//remove largest element
heap.remove(heap.bottom());
...

8 Comments

  1. First!

    Thanks for the update! I did hit a minor bug a version or two ago. When using LinkedObjectPool, the method “get” has an error where it’s an inline function that has multiple return statements giving the error:
    “Cannot inline a not final return”

    1. thanks for reporting, fixed in svn :)

  2. That fixed it- you’re the best!

  3. “Declaring a field in an interface is not supported in ActionScript 3.0″

    You can use getters/setters for declaring fields in interfaces:

    (AS3)
    interface Heapable implements Comparable {
    function get position ():Int;
    function set position (value:Int):void;
    }

    1. an implicit getter/setter is not a field, it’s a function that looks like a field.

  4. Absolutely. But as far as AS3 is concerned, fields and getters/setters are functionality equivalent (more or less), to the point that “declaring a field in an interface” might as well be possible.

    Rather than making sure consumers of your API remember to add the requisite properties to prevent runtime errors, you can add a getter/setter to your interface and the compiler will take on that responsibility. As a consumer, having to remember all that stuff is not tenable. And getters/setters have more benefits as well, which I’m sure you’re aware of.

    Love your work BTW. The articles on your site are top-notch :)

  5. Right, but as far as AS3 is concerned they are functionally equivalent (more or less). Rather than requiring that users of your API remember to add fields to their classes, you can add a getter/setter to your interface and let the compiler tell them. It’s less work for consumers and works the same as a property.

  6. Glidias

    Hi, for PriorityQueue, is there a way to have a priority queue using floating point priority numbers for comparison instead?

    I have a big issue with converting delta time in miliseconds (floating point number precision) into a suitably accruate priority:int value for use in CCD (continuous collision detection). Apparently, the collision pair being de-queued doesn’t match with the minT/minPair I recorded, so the priority values ain’t correct!!

Get Adobe Flash player