Summary

A min heap implementation in javascript.

Implementation of a min heap allowing for a comparator to be provided so that the heap may contain objects that involve a more complex comparison. This constructor constructs a MinHeap instance and takes two optional parameters: an array and comparator. If the array is provided, it will be used as the backing store for the heap. Therefore, all operations on the heap will be reflected in the provided array. Usage

Sample Usage

A few examples of usage using the various constructor elements.

Basic

This example show basic usage using default parameters. The heap will create an internal array and use that as the backing store. The items in the heap will be compared using natural order.

var heapq = new MinHeap(); heapq.push(5); heapq.push(2); heapq.push(1); heapq.pop()); // returns 1 heapq.pop()); // returns 2
Custom Item and Comparator

This example shows usage of a custom comparator used to order the tiems based on internal properties.

var heapq = new MinHeap(null, function(item1, item2) { return item1.k1 == item2.k1 ? 0 : item1.k1 < item2.k1 ? -1 : 1; }); var val1 = { f1 : "testx1", k1 : "key1" }; var val2 = { f1 : "testb2", k1 : "key2" }; var val3 = { f1 : "testc3", k1 : "key3" }; heapq.push(val1); heapq.push(val3); heapq.push(val2); assertEquals(val1, heapq.pop()); assertEquals(val2, heapq.pop()); assertEquals(val3, heapq.pop()); assertEquals(null, heapq.pop());