20 lines
488 B
TypeScript
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;
|
|
}
|