JavaScriptFundamental (ES6), part 2
Priority queue with a binary heap in JavaScript
109 A priority queue on a binary heap, and the tie it gets wrong
hardImplement a min-heap as a flat array: push sifts up, pop moves the last element to the root and sifts down. Expose peek and size. Prove the backing array is not in sorted order even though every pop comes out in order. Then find the flaw: two items of equal priority do not come out in the order they went in. Fix it with a sequence number in the comparator and prove the fix. Finish by using a bounded heap to find the three largest of a list without sorting it.
Stuck? Three hints, smallest first
- 1. For the node at
i, the parent is(i - 1) >> 1and the children are2i + 1and2i + 2. - 2. Sifting down means swapping with the smaller of the two children, and stopping when neither is smaller than you.
- 3. A heap cannot be stable, because sifting moves elements past each other. Break ties on an ever-increasing counter and stability is restored by the comparator, not by the heap.
class Heap {
constructor(compare) {
this.compare = compare;
this.items = [];
}
get size() { return this.items.length; }
peek() { return this.items.length ? this.items[0] : undefined; }
push(item) {
const a = this.items;
a.push(item);
let i = a.length - 1;
while (i > 0) {
const parent = (i - 1) >> 1;
if (this.compare(a[i], a[parent]) >= 0) break;
[a[i], a[parent]] = [a[parent], a[i]];
i = parent;
}
return this.size;
}
pop() {
const a = this.items;
if (a.length === 0) return undefined;
const top = a[0];
const last = a.pop();
if (a.length) {
a[0] = last;
let i = 0;
for (;;) {
const left = 2 * i + 1;
const right = left + 1;
let small = i;
if (left < a.length && this.compare(a[left], a[small]) < 0) small = left;
if (right < a.length && this.compare(a[right], a[small]) < 0) small = right;
if (small === i) break;
[a[i], a[small]] = [a[small], a[i]];
i = small;
}
}
return top;
}
}
const byNumber = (a, b) => a - b;
const numbers = new Heap(byNumber);
for (const n of [5, 3, 8, 1, 9, 2, 7]) numbers.push(n);
const rawArray = numbers.items.slice();
const rootIsSmallest = [numbers.peek(), numbers.size];
const drained = [];
while (numbers.size) drained.push(numbers.pop());
const emptyBehaviour = [numbers.pop(), numbers.peek(), numbers.size];
// Every parent no greater than its children, checked directly.
const shaped = new Heap(byNumber);
for (const n of [42, 17, 93, 4, 61, 8, 25, 3, 70, 51]) shaped.push(n);
let heapProperty = true;
for (let i = 1; i < shaped.items.length; i++) {
if (shaped.items[(i - 1) >> 1] > shaped.items[i]) heapProperty = false;
}
// Equal priorities, unstable.
const tickets = [
{ name: 'Adaeze', priority: 2 },
{ name: 'Bode', priority: 1 },
{ name: 'Chidi', priority: 2 },
{ name: 'Dayo', priority: 2 },
{ name: 'Emeka', priority: 1 },
{ name: 'Funke', priority: 2 },
];
const unstable = new Heap((a, b) => a.priority - b.priority);
for (const t of tickets) unstable.push(t);
const unstableOrder = [];
while (unstable.size) unstableOrder.push(unstable.pop().name);
const insertionOrderOfTwos = tickets.filter((t) => t.priority === 2).map((t) => t.name);
const poppedTwos = unstableOrder.filter((n) => insertionOrderOfTwos.includes(n));
let seq = 0;
const stable = new Heap((a, b) => a.priority - b.priority || a.seq - b.seq);
for (const t of tickets) stable.push({ ...t, seq: seq++ });
const stableOrder = [];
while (stable.size) stableOrder.push(stable.pop().name);
// Three largest, using a min-heap of at most three.
const readings = [12, 45, 3, 78, 23, 91, 6, 67, 34, 88, 19];
const topThree = new Heap(byNumber);
let heldAtRest = 0;
for (const r of readings) {
topThree.push(r);
if (topThree.size > 3) topThree.pop();
heldAtRest = Math.max(heldAtRest, topThree.size);
}
const largestThree = [];
while (topThree.size) largestThree.push(topThree.pop());
console.log('backing array :', rawArray);
console.log('popped :', drained);
console.log('unstable twos :', poppedTwos, 'vs insertion', insertionOrderOfTwos);
console.log('largest three :', largestThree);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the backing array is heap-ordered, and that is not the same as sorted', [rawArray, same(rawArray, [1, 2, 3, 5, 7, 8, 9])], [[1, 3, 2, 5, 9, 8, 7], false]);
test('yet the root is the smallest, and peek does not remove it', rootIsSmallest, [1, 7]);
test('popping repeatedly yields every item in order', drained, [1, 2, 3, 5, 7, 8, 9]);
test('an empty heap pops undefined instead of throwing', emptyBehaviour, [undefined, undefined, 0]);
test('every parent is no greater than its children after ten pushes', [heapProperty, shaped.items.length], [true, 10]);
test('equal priorities do NOT come out in the order they went in', [poppedTwos, same(poppedTwos, insertionOrderOfTwos)], [['Adaeze', 'Dayo', 'Chidi', 'Funke'], false]);
test('adding a sequence number to the comparator makes ties insertion-ordered', stableOrder, ['Bode', 'Emeka', 'Adaeze', 'Chidi', 'Dayo', 'Funke']);
test('a min-heap capped at three finds the three largest of eleven readings', largestThree, [78, 88, 91]);
test('having never held more than three of them at once', heldAtRest, 3);
A heap is the answer to a question sorting answers too well. Sorting gives total order for n log n; a heap gives you the minimum for log n per operation and never promises anything about the rest. The first assertion is that trade made visible — [1, 3, 2, 5, 9, 8, 7] is not sorted and never will be, it only guarantees each parent is no greater than its children, which is exactly enough for the root to be the minimum.
The instability in the sixth assertion is not a bug in this implementation, it is a property of the structure. Sifting swaps distant elements past one another, so two items that compare equal have no defined order at all — here Dayo, pushed fourth, comes out ahead of Chidi, pushed third, for no reason a caller could predict. Anyone who has watched a job queue run tasks of the same priority out of order has met this. The fix belongs in the comparator, not the heap: a monotonically increasing sequence number turns every tie into a strict comparison, and stability follows.
The last two assertions are the pattern worth stealing. To find the k largest of a stream, keep a min-heap of size k and evict the root whenever it overflows; the smallest of the survivors is always the one at hand to discard. It is O(n log k) with O(k) memory, so it works on a stream you cannot hold, where sort().slice(-3) needs all of it in memory first.