Skip to content

Instantly share code, notes, and snippets.

@xihai01
Created February 13, 2022 16:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xihai01/045cd00527f0ef7feebceca537d53f28 to your computer and use it in GitHub Desktop.
Save xihai01/045cd00527f0ef7feebceca537d53f28 to your computer and use it in GitHub Desktop.
BInary Search Implementation in JS
const binarySearch = function (array, target) {
// initialise variables to point to bounds of array
let bottom = 0;
let top = array.length - 1;
let middle;
while (bottom <= top) {
// get index of middle value
middle = Math.floor((bottom + top) / 2);
const middleValue = array[middle];
// return middle index if found
if (middleValue === target) {
return middle;
}
if (middleValue < target) {
bottom = middle + 1;
}
if (middleValue > target) {
top = middle - 1;
}
}
// return null if target not in array
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment