Skip to content

knotkit/heap

Binary and k-ary min/max heaps plus indexed priority queues, ordered by comparator you supply.

Four structures in one module: a binary heap, a k-ary heap, and an indexed priority queue over each. The first two hold values and answer “what is the best remaining item”. The priority queues hold keyed entries and answer it when a resident entry’s key changes, which is the case Dijkstra, Prim, and A* are built on.

time O(n) build, O(log n) push/pop, O(1) peek · space O(n), or O(n) plus a position index · Floyd's bottom-up heapify; updateKey is O(log n) through the index, never a search

The distinction that matters: a heap cannot find an entry it is holding, so re-keying one costs a linear search and a remove. An indexed priority queue keeps a position index, so updateKey(key, value) sifts in place. That is an algorithmic-class difference, and it is why the measured key-update comparison is 272× faster than heap-js linear remove plus push.

import { minBinaryHeap, minPriorityQueue, numberOrder } from 'knotkit/heap'
const heap = minBinaryHeap(numberOrder, [5, 8, 3])
heap.pop() // 3
const largest = minBinaryHeap(numberOrder, [5, 8, 3])
if (7 > largest.peek()) {
largest.replaceRoot(7) // returns 3; a fixed-size top-k
}
const queue = minPriorityQueue(numberOrder, [
[5, 'render'],
[1, 'parse'],
[3, 'layout'],
])
queue.updateKey(0, 'layout') // sifts in place, no search
queue.peek() // 'layout'

To keep the three largest values, hold a min heap and admit only values that beat its root: an inverted order is what makes an eviction structure out of a priority structure.

The kind table on this page carries the predicates; the short version is the operation mix.

If the workload is… Choose Because
pops at least as frequent as pushes, values only minBinaryHeap / maxBinaryHeap fewest comparisons per sift level at the same depth
pushes far outnumber pops, values only minKHeap / maxKHeap with k = 4 a flatter tree pays k comparisons over fewer levels
resident values are re-keyed minPriorityQueue / maxPriorityQueue O(1) lookup and an in-place sift; a heap cannot find its own entry
keys are dense integers and re-keying dominates denseIntegerMinPriorityQueue no value-to-index registry at all

Every layout, with the rule for choosing it:

FactoryChoose whenCost
minBinaryHeap
kind binary-min
the caller only pushes and pops values rather than re-keying residents, and the pop count is at least the push count2 comparisons per sift-down level, ceil(log2 n) levels
maxBinaryHeap
kind binary-max
the caller needs the largest value first and only pushes and pops values2 comparisons per sift-down level, ceil(log2 n) levels
minKHeap
kind k-min
pushes outnumber pops and n is at or above 10,000, where fewer sift-up levels repay the k comparisons per levelk comparisons per sift level, log_k n levels
maxKHeap
kind k-max
pushes outnumber pops, n is at or above 10,000, and the caller needs the largest value firstk comparisons per sift level, log_k n levels
minPriorityQueue
kind binary-priority-queue-min
resident values require in-place re-keying, the dense numeric domain is unavailable, and pop count is at least the decrease-key count2 comparisons per sift level plus one Map lookup per key read
maxPriorityQueue
kind binary-priority-queue-max
resident values must be re-keyed in place and the caller needs the largest key first2 comparisons per sift level plus one Map lookup per key read
minKPriorityQueue
kind k-priority-queue-min
decrease-key calls outnumber pops and n is at or above 10,000k comparisons per sift level, log_k n levels, plus one Map lookup per key read
maxKPriorityQueue
kind k-priority-queue-max
decrease-key calls outnumber pops, n is at or above 10,000, and the caller needs the largest key firstk comparisons per sift level, log_k n levels, plus one Map lookup per key read
denseIntegerMinPriorityQueue
kind dense-integer-priority-queue-min
numeric keys require resident decrease-key and values index a known fixed dense integer domainO(capacity) space with constant-time direct position lookup and two comparisons per sift-down level

Performance and benchmarks for this module

A wider arity is a trade, not an upgrade: it makes each level more expensive and each path shorter.

Drag the arity and the heap size: every change reruns the module’s own demo against knotkit/heap in your browser, counting comparator calls by wrapping the Order the heap takes as a parameter. The defaults reproduce the README figure.

{"v":1,"box":[44.9462,94.1597,913.7333,444.3555],"x":{"s":"log","lim":[26.5382254661,2469.49443111],"inv":false,"g":0,"t":"Heap size (items)","tk":[[32,"32"],[64,"64"],[128,"128"],[256,"256"],[512,"512"],[1024,"1,024"],[2048,"2,048"]],"b":10},"y":{"s":"linear","lim":[0,16],"inv":false,"g":0,"tk":[[0,"0"],[5,"5"],[10,"10"],[16,"16"]]},"ti":"Pop: 4-ary makes 53% more comparisons at 2,048","a":[{"k":"line","c":"#fffff8","s":"x","d":[32,3.6875,64,4.8125,128,5.734375,256,6.72265625,512,7.724609375,1024,8.693359375,2048,9.71435546875],"p":[80.81,363.65,213.66,339.02,346.5,318.85,479.34,297.22,612.18,275.29,745.02,254.08,877.87,231.74]},{"k":"line","c":"#1d5fa6","s":"x","d":[32,3.6875,64,4.8125,128,5.734375,256,6.72265625,512,7.724609375,1024,8.693359375,2048,9.71435546875],"p":[80.81,363.65,213.66,339.02,346.5,318.85,479.34,297.22,612.18,275.29,745.02,254.08,877.87,231.74]},{"k":"line","c":"#fffff8","s":"x","d":[32,5.78125,64,7.203125,128,8.7734375,256,10.30859375,512,11.822265625,1024,13.3486328125,2048,14.8837890625],"p":[80.81,317.82,213.66,286.7,346.5,252.33,479.34,218.73,612.18,185.6,745.02,152.19,877.87,118.59]},{"k":"line","c":"#c4501b","s":"x","d":[32,5.78125,64,7.203125,128,8.7734375,256,10.30859375,512,11.822265625,1024,13.3486328125,2048,14.8837890625],"p":[80.81,317.82,213.66,286.7,346.5,252.33,479.34,218.73,612.18,185.6,745.02,152.19,877.87,118.59]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"}],"lg":[]} 32 64 128 256 512 1,024 2,048 Heap size (items) 0 5 10 16 Comparisons per pop while draining Binary: 9.7 4-ary: 14.9 Pop: 4-ary makes 53% more comparisons at 2,048 {"v":1,"box":[44.9462,605.1597,913.7333,955.3555],"x":{"s":"log","lim":[26.5382254661,2469.49443111],"inv":false,"g":1,"t":"Heap size (items)","tk":[[32,"32"],[64,"64"],[128,"128"],[256,"256"],[512,"512"],[1024,"1,024"],[2048,"2,048"]],"b":10},"y":{"s":"linear","lim":[0,16],"inv":false,"g":1,"tk":[[0,"0"],[5,"5"],[10,"10"],[16,"16"]]},"ti":"Decrease key: 4-ary makes 40% fewer at 2,048","a":[{"k":"line","c":"#fffff8","s":"x","d":[32,4.84375,64,5.765625,128,6.7734375,256,7.77734375,512,8.771484375,1024,9.7451171875,2048,10.736328125],"p":[80.81,849.34,213.66,829.16,346.5,807.1,479.34,785.13,612.18,763.37,745.02,742.06,877.87,720.37]},{"k":"line","c":"#1d5fa6","s":"x","d":[32,4.84375,64,5.765625,128,6.7734375,256,7.77734375,512,8.771484375,1024,9.7451171875,2048,10.736328125],"p":[80.81,849.34,213.66,829.16,346.5,807.1,479.34,785.13,612.18,763.37,745.02,742.06,877.87,720.37]},{"k":"line","c":"#fffff8","s":"x","d":[32,3.4375,64,3.84375,128,4.3984375,256,4.8515625,512,5.396484375,1024,5.8388671875,2048,6.39013671875],"p":[80.81,880.12,213.66,871.23,346.5,859.09,479.34,849.17,612.18,837.24,745.02,827.56,877.87,815.49]},{"k":"line","c":"#c4501b","s":"x","d":[32,3.4375,64,3.84375,128,4.3984375,256,4.8515625,512,5.396484375,1024,5.8388671875,2048,6.39013671875],"p":[80.81,880.12,213.66,871.23,346.5,859.09,479.34,849.17,612.18,837.24,745.02,827.56,877.87,815.49]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"}],"lg":[]} 32 64 128 256 512 1,024 2,048 Heap size (items) 0 5 10 16 Comparisons per indexed priority decrease Binary: 10.7 4-ary: 6.4 Decrease key: 4-ary makes 40% fewer at 2,048
{"v":1,"box":[44.9462,122.3921,462.5675,444.3555],"x":{"s":"log","lim":[26.5382254661,2469.49443111],"inv":false,"g":0,"t":"Heap size (items)","tk":[[32,"32"],[64,"64"],[128,"128"],[256,"256"],[512,"512"],[1024,"1,024"],[2048,"2,048"]],"b":10},"y":{"s":"linear","lim":[0,16],"inv":false,"g":0,"tk":[[0,"0"],[5,"5"],[10,"10"],[16,"16"]]},"ti":"Pop: 4-ary makes 53% more comparisons at\n2,048","a":[{"k":"line","c":"#fffff8","s":"x","d":[32,3.6875,64,4.8125,128,5.734375,256,6.72265625,512,7.724609375,1024,8.693359375,2048,9.71435546875],"p":[62.19,370.15,126.04,347.51,189.9,328.96,253.76,309.08,317.61,288.92,381.47,269.42,445.33,248.88]},{"k":"line","c":"#1d5fa6","s":"x","d":[32,3.6875,64,4.8125,128,5.734375,256,6.72265625,512,7.724609375,1024,8.693359375,2048,9.71435546875],"p":[62.19,370.15,126.04,347.51,189.9,328.96,253.76,309.08,317.61,288.92,381.47,269.42,445.33,248.88]},{"k":"line","c":"#fffff8","s":"x","d":[32,5.78125,64,7.203125,128,8.7734375,256,10.30859375,512,11.822265625,1024,13.3486328125,2048,14.8837890625],"p":[62.19,328.02,126.04,299.41,189.9,267.81,253.76,236.92,317.61,206.46,381.47,175.74,445.33,144.85]},{"k":"line","c":"#c4501b","s":"x","d":[32,5.78125,64,7.203125,128,8.7734375,256,10.30859375,512,11.822265625,1024,13.3486328125,2048,14.8837890625],"p":[62.19,328.02,126.04,299.41,189.9,267.81,253.76,236.92,317.61,206.46,381.47,175.74,445.33,144.85]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"}],"lg":[]} 32 64 128 256 512 1,024 2,048 Heap size (items) 0 5 10 16 Comparisons per pop while draining Binary: 9.7 4-ary: 14.9 Pop: 4-ary makes 53% more comparisons at 2,048 {"v":1,"box":[44.9462,633.3921,462.5675,955.3555],"x":{"s":"log","lim":[26.5382254661,2469.49443111],"inv":false,"g":1,"t":"Heap size (items)","tk":[[32,"32"],[64,"64"],[128,"128"],[256,"256"],[512,"512"],[1024,"1,024"],[2048,"2,048"]],"b":10},"y":{"s":"linear","lim":[0,16],"inv":false,"g":1,"tk":[[0,"0"],[5,"5"],[10,"10"],[16,"16"]]},"ti":"Decrease key: 4-ary makes 40% fewer at\n2,048","a":[{"k":"line","c":"#fffff8","s":"x","d":[32,4.84375,64,5.765625,128,6.7734375,256,7.77734375,512,8.771484375,1024,9.7451171875,2048,10.736328125],"p":[62.19,857.89,126.04,839.34,189.9,819.06,253.76,798.85,317.61,778.85,381.47,759.26,445.33,739.31]},{"k":"line","c":"#1d5fa6","s":"x","d":[32,4.84375,64,5.765625,128,6.7734375,256,7.77734375,512,8.771484375,1024,9.7451171875,2048,10.736328125],"p":[62.19,857.89,126.04,839.34,189.9,819.06,253.76,798.85,317.61,778.85,381.47,759.26,445.33,739.31]},{"k":"line","c":"#fffff8","s":"x","d":[32,3.4375,64,3.84375,128,4.3984375,256,4.8515625,512,5.396484375,1024,5.8388671875,2048,6.39013671875],"p":[62.19,886.18,126.04,878.01,189.9,866.85,253.76,857.73,317.61,846.76,381.47,837.86,445.33,826.77]},{"k":"line","c":"#c4501b","s":"x","d":[32,3.4375,64,3.84375,128,4.3984375,256,4.8515625,512,5.396484375,1024,5.8388671875,2048,6.39013671875],"p":[62.19,886.18,126.04,878.01,189.9,866.85,253.76,857.73,317.61,846.76,381.47,837.86,445.33,826.77]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"}],"lg":[]} 32 64 128 256 512 1,024 2,048 Heap size (items) 0 5 10 16 Comparisons per indexed priority decrease Binary: 10.7 4-ary: 6.4 Decrease key: 4-ary makes 40% fewer at 2,048
  • On 2,048 seeded keys, drain comparisons per pop are 9.7 / 14.9 for 2 / 4 children.
  • Indexed updates move item 2047 to priority -2048 without inserting a second entry.
  • The plots count comparator calls after construction.

Hover or focus a chart for exact values. Each change reruns demo.ts against knotkit/heap in your browser; the defaults reproduce the README figure.

A wider heap pays more comparisons per pop and fewer per decrease. The right arity follows your workload’s mix of the two, which is why the module states it as a rule rather than a default.

Heaps persist through a second entrypoint, knotkit/heap/wire, which is where the parser lives; importing knotkit/heap never loads it. Both binary and JSON formats are versioned, and a decoded structure is checked against the heap invariant rather than trusted — a truncated artifact fails with a code (MISSING_NODES, HEAP_INVARIANT_VIOLATION) instead of producing a heap that quietly lies about its order.

ExportReturnsDoes
minBinaryHeapBinaryHeap<A>Binary min heap over any order; O(n) Floyd build from an iterable.
maxBinaryHeapBinaryHeap<A>Binary max heap over any order; O(n) Floyd build from an iterable.
minKHeapKHeap<A>k-ary min heap; `k` is the arity and is taken first.
maxKHeapKHeap<A>k-ary max heap; `k` is the arity and is taken first.
minPriorityQueueBinaryPriorityQueue<K, V>Indexed binary min queue: unique values, O(1) key lookup, in-place decrease-key.
maxPriorityQueueBinaryPriorityQueue<K, V>Indexed binary max queue: unique values, O(1) key lookup, in-place decrease-key.
minKPriorityQueueKPriorityQueue<K, V>Indexed k-ary min queue; `k` is the arity and is taken first.
maxKPriorityQueueKPriorityQueue<K, V>Indexed k-ary max queue; `k` is the arity and is taken first.
makeOrderOrder<A>Build an order from a `(a, b) => number` comparator, short-circuiting on referential equality.
reverseOrderOrder<A>Flip an order's direction, turning a min-comparator into a max-comparator.
mapInputOrderOrder<B>Derive an order on `B` by projecting each value to an `A` first.
denseIntegerMinPriorityQueueDenseIntegerPriorityQueuePreallocate a known dense integer domain for a numeric min queue with direct-index decrease-key.

Cost per member. Open a row for every operation.

minBinaryHeap 8 members
MemberCost
peekO(1)
popO(log n)
replaceRootO(log n)
pushO(log n)
sizeO(1)
clearO(1)
valuesO(n)
[Symbol.iterator]O(n)
maxBinaryHeap 8 members
MemberCost
peekO(1)
popO(log n)
replaceRootO(log n)
pushO(log n)
sizeO(1)
clearO(1)
valuesO(n)
[Symbol.iterator]O(n)
minKHeap 8 members
MemberCost
peekO(1)
popO(k log_k n)
replaceRootO(k log_k n)
pushO(log_k n)
sizeO(1)
clearO(1)
valuesO(n)
[Symbol.iterator]O(n)
maxKHeap 8 members
MemberCost
peekO(1)
popO(k log_k n)
replaceRootO(k log_k n)
pushO(log_k n)
sizeO(1)
clearO(1)
valuesO(n)
[Symbol.iterator]O(n)
minPriorityQueue 8 members
MemberCost
peekO(1)
popO(log n)
pushO(log n)
updateKeyO(log n)
keyOfO(1) average
clearO(n)
entriesO(n)
[Symbol.iterator]O(n)
maxPriorityQueue 8 members
MemberCost
peekO(1)
popO(log n)
pushO(log n)
updateKeyO(log n)
keyOfO(1) average
clearO(n)
entriesO(n)
[Symbol.iterator]O(n)
minKPriorityQueue 8 members
MemberCost
peekO(1)
popO(k log_k n)
pushO(log_k n)
updateKeyO(k log_k n)
keyOfO(1) average
clearO(n)
entriesO(n)
[Symbol.iterator]O(n)
maxKPriorityQueue 8 members
MemberCost
peekO(1)
popO(k log_k n)
pushO(log_k n)
updateKeyO(k log_k n)
keyOfO(1) average
clearO(n)
entriesO(n)
[Symbol.iterator]O(n)
denseIntegerMinPriorityQueue 14 members
MemberCost
constructionO(capacity + entries)
capacityO(1)
sizeO(1)
hasO(1)
keyOfO(1)
peekO(1)
peekEntryO(1)
pushO(log n)
popO(log n)
popEntryO(log n)
updateKeyO(log n)
clearO(n)
entriesO(n)
[Symbol.iterator]O(n)

Every error this module throws is HeapInvalidInputError or HeapParseError, with a code from a closed, exported list. Branch on the code; the message is for people.

HeapInvalidInputError
EMPTY INVALID_ARITY INVALID_CAPACITY DUPLICATE_VALUE INVALID_VALUE
HeapParseError
VALUE_NOT_FOUND FOREIGN_STRUCTURE MISSING_ELEMENT_CODEC INVALID_CODEC_RESULT NON_INJECTIVE_CODEC SERIALIZATION_LIMIT_EXCEEDED INVALID_SHAPE UNSUPPORTED_SCHEMA_VERSION UNKNOWN_KIND MISSING_NODES MISSING_ENTRIES HEAP_INVARIANT_VIOLATION INVALID_ELEMENT INVALID_KEY INVALID_MAGIC UNSUPPORTED_ENVELOPE_VERSION UNSUPPORTED_PAYLOAD_VERSION INVALID_SECTION_GEOMETRY NONZERO_PADDING MISALIGNED_SECTION TRUNCATED_PAYLOAD DECODE_BUDGET_EXCEEDED UNSTABLE_BUFFER WRONG_FORMAT INTEGRITY_MISMATCH INVALID_PACKAGE_HEADER
If you need to…Use instead
sort a fixed array onceArray.prototype.sort with a comparator
an exact set or map, with no orderingSet, Map
remove an arbitrary resident entry, or cancel a queued taska Map plus a heap of stale entries re-checked on pop; delete is not implemented
track which elements are connected, and merge groupsknotkit/disjoint-set
count distinct values or estimate frequencies in bounded memoryknotkit/scalar-sketch
decrease-key when values are sparse or arbitrary, or the dense integer domain capacity is unknownminPriorityQueue (binary-priority-queue-min) from knotkit/heap
Prompt · knotkit/heap
Use knotkit/heap for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/heap'.

Exports:
- `minBinaryHeap` → `BinaryHeap<A>`: Binary min heap over any order; O(n) Floyd build from an iterable.
- `maxBinaryHeap` → `BinaryHeap<A>`: Binary max heap over any order; O(n) Floyd build from an iterable.
- `minKHeap` → `KHeap<A>`: k-ary min heap; `k` is the arity and is taken first.
- `maxKHeap` → `KHeap<A>`: k-ary max heap; `k` is the arity and is taken first.
- `minPriorityQueue` → `BinaryPriorityQueue<K, V>`: Indexed binary min queue: unique values, O(1) key lookup, in-place decrease-key.
- `maxPriorityQueue` → `BinaryPriorityQueue<K, V>`: Indexed binary max queue: unique values, O(1) key lookup, in-place decrease-key.
- `minKPriorityQueue` → `KPriorityQueue<K, V>`: Indexed k-ary min queue; `k` is the arity and is taken first.
- `maxKPriorityQueue` → `KPriorityQueue<K, V>`: Indexed k-ary max queue; `k` is the arity and is taken first.
- `makeOrder` → `Order<A>`: Build an order from a `(a, b) => number` comparator, short-circuiting on referential equality.
- `reverseOrder` → `Order<A>`: Flip an order's direction, turning a min-comparator into a max-comparator.
- `mapInputOrder` → `Order<B>`: Derive an order on `B` by projecting each value to an `A` first.
- `denseIntegerMinPriorityQueue` → `DenseIntegerPriorityQueue`: Preallocate a known dense integer domain for a numeric min queue with direct-index decrease-key.

Pick the layout by these rules:
- `minBinaryHeap` (kind 'binary-min') when the caller only pushes and pops values rather than re-keying residents, and the pop count is at least the push count
- `maxBinaryHeap` (kind 'binary-max') when the caller needs the largest value first and only pushes and pops values
- `minKHeap` (kind 'k-min') when pushes outnumber pops and n is at or above 10,000, where fewer sift-up levels repay the k comparisons per level
- `maxKHeap` (kind 'k-max') when pushes outnumber pops, n is at or above 10,000, and the caller needs the largest value first
- `minPriorityQueue` (kind 'binary-priority-queue-min') when resident values require in-place re-keying, the dense numeric domain is unavailable, and pop count is at least the decrease-key count
- `maxPriorityQueue` (kind 'binary-priority-queue-max') when resident values must be re-keyed in place and the caller needs the largest key first
- `minKPriorityQueue` (kind 'k-priority-queue-min') when decrease-key calls outnumber pops and n is at or above 10,000
- `maxKPriorityQueue` (kind 'k-priority-queue-max') when decrease-key calls outnumber pops, n is at or above 10,000, and the caller needs the largest key first
- `denseIntegerMinPriorityQueue` (kind 'dense-integer-priority-queue-min') when numeric keys require resident decrease-key and values index a known fixed dense integer domain

Inputs and their sources:
- ordering: `Order<A>` from `knotkit/heap`
- ordering on restore, which no artifact carries: `Order<A>` from `knotkit/heap`

Use something else when:
- sort a fixed array once → Array.prototype.sort with a comparator
- an exact set or map, with no ordering → Set, Map
- remove an arbitrary resident entry, or cancel a queued task → a Map plus a heap of stale entries re-checked on pop; delete is not implemented
- track which elements are connected, and merge groups → knotkit/disjoint-set
- count distinct values or estimate frequencies in bounded memory → knotkit/scalar-sketch
- decrease-key when values are sparse or arbitrary, or the dense integer domain capacity is unknown → minPriorityQueue (binary-priority-queue-min) from knotkit/heap

Errors are HeapInvalidInputError or HeapParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/heap/wire` (serializeHeap, deserializeHeap, serializeHeapJson, deserializeHeapJson, serializePriorityQueue, deserializePriorityQueue, serializePriorityQueueJson, deserializePriorityQueueJson).

Full page: https://knotkit.jkomyno.dev/modules/heap.md
Types: node_modules/knotkit/heap/ and https://knotkit.jkomyno.dev/reference/knotkit/heap/