tests/sims/binarysearch.test.ts
The automated tests for the /simulators/binary-search simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.
- On 2,000 sorted arrays with duplicates, find, lower bound and upper bound agree with a linear scan for every target.
- No search takes more steps than the worst case, floor(log2 n) + 1 probes.
- The (lo + hi) / 2 midpoint overflows a 32-bit int where lo + (hi - lo) / 2 does not.
// /simulators/binary-search: exact match, lower bound and upper bound, against a linear scan.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { search, makeArray, worst, midOverflow, midSafe } from '../../src/lib/sims/binarySearch.ts';
import { checker } from './check.ts';
test('on 2,000 sorted arrays with duplicates, find, lower bound and upper bound agree with a linear scan for every target', () => {
const { ok, done } = checker();
for (let seed = 1; seed <= 2000; seed++) {
const n = seed % 60, a = makeArray(n, seed);
for (let t = 0; t <= (a[n - 1] ?? 5) + 3; t++) {
const f = search(a, t, 'find'), lo = search(a, t, 'lower'), up = search(a, t, 'upper');
const refLo = a.findIndex((x) => x >= t), refUp = a.findIndex((x) => x > t);
ok(f.found === a.includes(t) && (!f.found || a[f.index] === t), `find ${t} in [${a}]`);
ok(lo.index === (refLo < 0 ? n : refLo), `lower bound of ${t} in [${a}]: ${lo.index}`);
ok(up.index === (refUp < 0 ? n : refUp), `upper bound of ${t} in [${a}]: ${up.index}`);
}
}
done();
});
test('no search takes more steps than the worst case, floor(log2 n) + 1 probes', () => {
const { ok, done } = checker();
for (let seed = 1; seed <= 2000; seed++) {
const n = seed % 60, a = makeArray(n, seed);
for (let t = 0; t <= (a[n - 1] ?? 5) + 3; t++) {
const f = search(a, t, 'find'), lo = search(a, t, 'lower');
ok(f.steps.length <= worst(n), `find took ${f.steps.length} steps on n=${n}, worst is ${worst(n)}`);
ok(lo.steps.length <= Math.ceil(Math.log2(n + 1)), `lower bound took ${lo.steps.length} steps on n=${n}`);
}
}
assert.equal(worst(1e6), 20);
assert.equal(worst(1e9), 30);
done();
});
test('the (lo + hi) / 2 midpoint overflows a 32-bit int where lo + (hi - lo) / 2 does not', () => {
const lo = 1_200_000_000, hi = 1_300_000_000;
assert.ok(lo + hi > 2 ** 31 - 1);
// Java: (lo + hi) wraps to 2,500,000,000 - 2^32 = -1,794,967,296, and int division by 2 gives -897,483,648
assert.equal(midOverflow(lo, hi), (lo + hi - 2 ** 32) / 2);
assert.equal(midOverflow(lo, hi), -897_483_648);
assert.equal(midSafe(lo, hi), 1_250_000_000);
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.