Skip to content

Instantly share code, notes, and snippets.

@tcelovsky
Created July 9, 2021 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcelovsky/dd455f417bd0eb09abd3db54e55b9f4a to your computer and use it in GitHub Desktop.
Save tcelovsky/dd455f417bd0eb09abd3db54e55b9f4a to your computer and use it in GitHub Desktop.
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