Skip to content

Instantly share code, notes, and snippets.

@RinatValiullov
Last active December 8, 2017 10:44
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 RinatValiullov/3a2f49a5e67487e2d1c5de3e341242b2 to your computer and use it in GitHub Desktop.
Save RinatValiullov/3a2f49a5e67487e2d1c5de3e341242b2 to your computer and use it in GitHub Desktop.
Binary Search Algorithm
/* We can only use binary search if the input array of numbers is already sorted! */
let binarySearch = (target, numbers) => {
/* find an apearance of target in numbers */
/*
** we have lowLimit and highLimit of our range(numbers)
** so starting point is -1 (the 0th index)
*/
let lowLimit = -1;
let highLimit = numbers.length;
/*
** if there isn't at least 1 index between lowLimit and highLimit,
** we've run out of guesses and the number must not be present
*/
while ( (lowLimit + 1) < highLimit ) {
/*
** find the index ~halfway between the lowLimit and highLimit
** we have to round down, to avoid getting a "half index"
*/
let distance = highLimit - lowLimit;
let halfDistance = Math.floor(distance / 2);
let guessIndex = lowLimit + halfDistance;
let guessValue = numbers[guessIndex];
if (guessValue === target) {
return true;
}
if (guessValue > target) {
/* target is to the left, so move high boundary to the left */
highLimit = guessIndex;
} else {
/* target is to the right, so move low boundary to the right */
lowLimit = guessIndex;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment