tests/sims/bigo.test.ts
The automated tests for the /simulators/big-o-race 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.
- The inputs are real permutations, and the insertion sort count equals running the sort and counting.
- A failed binary search over n items makes exactly floor(log2 n) + 1 comparisons.
- Merge sort never exceeds Knuth's worst case n*ceil(lg n) - 2^ceil(lg n) + 1 comparisons, up to a million items.
- Growing an array by doubling copies 2^20 - 1 elements in total over a million appends.
// /simulators/big-o-race: operation counts for constant, log, linear, n log n and quadratic algorithms.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { permutation, insertionSortComparisons, insertionSortRun, binarySearchComparisons, measure, doublingCopies } from '../../src/lib/sims/bigO.ts';
import { checker } from './check.ts';
test('the inputs are real permutations, and the insertion sort count equals running the sort and counting', () => {
const { ok, done } = checker();
for (let s = 1; s <= 300; s++) {
const n = 1 + ((s * 37) % 2500), a = permutation(n, s);
ok(Array.from(a).sort((x, y) => x - y).every((v, i) => v === i), `seed ${s} is not a permutation of 0..${n - 1}`);
ok(insertionSortComparisons(a) === insertionSortRun(a), `insertion sort count on n=${n}`);
}
done();
});
test('a failed binary search over n items makes exactly floor(log2 n) + 1 comparisons', () => {
const { ok, done } = checker();
for (let n = 1; n <= 5000; n++) ok(binarySearchComparisons(n, n) === Math.floor(Math.log2(n)) + 1, `n=${n}: ${binarySearchComparisons(n, n)}`);
done();
});
test("merge sort never exceeds Knuth's worst case n*ceil(lg n) - 2^ceil(lg n) + 1 comparisons, up to a million items", () => {
for (const n of [10, 100, 1000, 10000, 100000, 1000000]) {
const L = Math.ceil(Math.log2(n));
const m = measure(n, 7);
assert.ok(m.nlogn <= n * L - 2 ** L + 1, `n=${n}: ${m.nlogn} comparisons`);
}
});
test('growing an array by doubling copies 2^20 - 1 elements in total over a million appends', () => {
assert.equal(doublingCopies(1e6), 2 ** 20 - 1);
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.