Files
exercise-typescript/typescript/binary-search/binary-search.ts
2022-11-09 20:30:56 +01:00

20 lines
488 B
TypeScript

export function find(
haystack: number[],
needle: number,
start: number = 0,
end: number = haystack.length - 1
): number | never {
if (start > end || end < start) {
throw new Error("Value not in array");
}
const index = start + Math.floor((end - start) / 2);
const value = haystack[index];
if (needle > value) {
return find(haystack, needle, index + 1, end);
}
if (needle < value) {
return find(haystack, needle, start, index - 1);
}
return index;
}