Binary search
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user