Skip to content

Instantly share code, notes, and snippets.

@Hoyasumii
Created August 23, 2024 14:47
Show Gist options
  • Save Hoyasumii/34c730e8121e953b364fcd9ec75fad99 to your computer and use it in GitHub Desktop.
Save Hoyasumii/34c730e8121e953b364fcd9ec75fad99 to your computer and use it in GitHub Desktop.
BinarySearch
function binarySearch(value: number, data: Array<number>): number | undefined {
let low: number = 0;
let high: number = data.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (data[mid] === value) {
return mid;
} else if (data[mid] < value) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return undefined;
}
let value = 50_500_000;
const values: Array<number> = Array.from(
{ length: 200_000_000 },
(_, index) => index
);
console.log("Binary Search: O(log n)");
console.time("Data");
console.log(binarySearch(value, values));
console.timeEnd("Data");
console.log("Binary Search: O(n)");
console.time("Timing");
console.log(values.find((item) => item === value));
console.timeEnd("Timing");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment