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.
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 searchqueue.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.
Which layout, and why
Section titled “Which layout, and why”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:
| Factory | Choose when | Cost |
|---|---|---|
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 count | 2 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 values | 2 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 level | k 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 first | k 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 count | 2 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 first | 2 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,000 | k 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 first | k 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 domain | O(capacity) space with constant-time direct position lookup and two comparisons per sift-down level |
A wider arity is a trade, not an upgrade: it makes each level more expensive and each path shorter.
Count the comparisons
Section titled “Count the comparisons”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.
- 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.
Save and restore
Section titled “Save and restore”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.
| Export | Returns | Does |
|---|---|---|
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. |
Cost per member. Open a row for every operation.
minBinaryHeap 8 members
| Member | Cost |
|---|---|
peek | O(1) |
pop | O(log n) |
replaceRoot | O(log n) |
push | O(log n) |
size | O(1) |
clear | O(1) |
values | O(n) |
[Symbol.iterator] | O(n) |
maxBinaryHeap 8 members
| Member | Cost |
|---|---|
peek | O(1) |
pop | O(log n) |
replaceRoot | O(log n) |
push | O(log n) |
size | O(1) |
clear | O(1) |
values | O(n) |
[Symbol.iterator] | O(n) |
minKHeap 8 members
| Member | Cost |
|---|---|
peek | O(1) |
pop | O(k log_k n) |
replaceRoot | O(k log_k n) |
push | O(log_k n) |
size | O(1) |
clear | O(1) |
values | O(n) |
[Symbol.iterator] | O(n) |
maxKHeap 8 members
| Member | Cost |
|---|---|
peek | O(1) |
pop | O(k log_k n) |
replaceRoot | O(k log_k n) |
push | O(log_k n) |
size | O(1) |
clear | O(1) |
values | O(n) |
[Symbol.iterator] | O(n) |
minPriorityQueue 8 members
| Member | Cost |
|---|---|
peek | O(1) |
pop | O(log n) |
push | O(log n) |
updateKey | O(log n) |
keyOf | O(1) average |
clear | O(n) |
entries | O(n) |
[Symbol.iterator] | O(n) |
maxPriorityQueue 8 members
| Member | Cost |
|---|---|
peek | O(1) |
pop | O(log n) |
push | O(log n) |
updateKey | O(log n) |
keyOf | O(1) average |
clear | O(n) |
entries | O(n) |
[Symbol.iterator] | O(n) |
minKPriorityQueue 8 members
| Member | Cost |
|---|---|
peek | O(1) |
pop | O(k log_k n) |
push | O(log_k n) |
updateKey | O(k log_k n) |
keyOf | O(1) average |
clear | O(n) |
entries | O(n) |
[Symbol.iterator] | O(n) |
maxKPriorityQueue 8 members
| Member | Cost |
|---|---|
peek | O(1) |
pop | O(k log_k n) |
push | O(log_k n) |
updateKey | O(k log_k n) |
keyOf | O(1) average |
clear | O(n) |
entries | O(n) |
[Symbol.iterator] | O(n) |
denseIntegerMinPriorityQueue 14 members
| Member | Cost |
|---|---|
construction | O(capacity + entries) |
capacity | O(1) |
size | O(1) |
has | O(1) |
keyOf | O(1) |
peek | O(1) |
peekEntry | O(1) |
push | O(log n) |
pop | O(log n) |
popEntry | O(log n) |
updateKey | O(log n) |
clear | O(n) |
entries | O(n) |
[Symbol.iterator] | O(n) |
Errors
Section titled “Errors”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.
HeapInvalidInputErrorEMPTYINVALID_ARITYINVALID_CAPACITYDUPLICATE_VALUEINVALID_VALUEHeapParseErrorVALUE_NOT_FOUNDFOREIGN_STRUCTUREMISSING_ELEMENT_CODECINVALID_CODEC_RESULTNON_INJECTIVE_CODECSERIALIZATION_LIMIT_EXCEEDEDINVALID_SHAPEUNSUPPORTED_SCHEMA_VERSIONUNKNOWN_KINDMISSING_NODESMISSING_ENTRIESHEAP_INVARIANT_VIOLATIONINVALID_ELEMENTINVALID_KEYINVALID_MAGICUNSUPPORTED_ENVELOPE_VERSIONUNSUPPORTED_PAYLOAD_VERSIONINVALID_SECTION_GEOMETRYNONZERO_PADDINGMISALIGNED_SECTIONTRUNCATED_PAYLOADDECODE_BUDGET_EXCEEDEDUNSTABLE_BUFFERWRONG_FORMATINTEGRITY_MISMATCHINVALID_PACKAGE_HEADER
When not to use it
Section titled “When not to use it”| If you need to… | Use instead |
|---|---|
| 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 |
Prompt an agent
Section titled “Prompt an agent”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/See also
Section titled “See also”- API referenceevery type and signature
- Capability recordthis page as JSON, also in the installed package
- Edit this page on GitHubsuggest a change to the source record