Skip to content

Binary search over sorted ids

Finding an id in a sorted list. Tests for a found id and a missing id both pass, but indexOfId([10, 20, 30], 10) returns -1: when the search narrows down to one last element, the loop stops before looking at it.

src/ids.ts
export function indexOfId(ids: readonly number[], target: number): number {
let lo = 0;
let hi = ids.length - 1;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (ids[mid] < target) lo = mid + 1;
else if (ids[mid] > target) hi = mid - 1;
else return mid;
}
return -1;
}

See how Dafny finds and fixes it.

Last updated: