Heaps
Factor handbook » The language » Collections

Prev:Interval maps
Next:Boxes


A heap is an implementation of a priority queue, which is a structure that maintains a sorted set of elements. The key property is that insertion of an arbitrary element and removal of the first element (determined by order) is performed in O(log n) time.

Heap elements are key/value pairs and are compared using the <=> generic word on the first element of the pair.

There are two classes of heaps. Min-heaps sort their elements so that the minimum element is first:
Image
min-heap

Image
min-heap? ( object -- ? )

Image
<min-heap> ( -- min-heap )


Max-heaps sort their elements so that the maximum element is first:
Image
max-heap

Image
max-heap? ( object -- ? )

Image
<max-heap> ( -- max-heap )


Both obey a protocol.

Queries:
Image
heap-empty? ( heap -- ? )

Image
heap-size ( heap -- n )

Image
heap-peek ( heap -- value key )


Insertion:
Image
heap-push ( value key heap -- )

Image
heap-push* ( value key heap -- entry )

Image
heap-push-all ( assoc heap -- )


Removal:
Image
heap-pop* ( heap -- )

Image
heap-pop ( heap -- value key )

Image
heap-delete ( entry heap -- )


Processing heaps:
Image
slurp-heap ( ... heap quot: ( ... value key -- ... ) -- ... )