Skip to content

Instantly share code, notes, and snippets.

@tcelovsky
Created Jul 9, 2021
Embed
What would you like to do?
O(log n) Example
const array = [1, 2, 4, 8 ,16, 32, 64, 128, 256];
const number = 128;
function binarySearch(array, number) {
let startIndex = 0;
let endIndex = (array.length) - 1;
while (startIndex <= endIndex) {
let pivot = Math.floor((startIndex + endIndex)/2);
if (array[pivot] === number) {
return `Located ${number} at ${pivot}`;
} else if (array[pivot] < number) {
startIndex = pivot + 1;
} else {
endIndex = pivot - 1;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment