Skip to content

Instantly share code, notes, and snippets.

@jochasinga
Created February 5, 2017 22:09
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 jochasinga/c6812b54d8a8d5df04eb53173751f3b0 to your computer and use it in GitHub Desktop.
Save jochasinga/c6812b54d8a8d5df04eb53173751f3b0 to your computer and use it in GitHub Desktop.
Binary search a sorted array.
function search(dst, arr) {
// sort the input array
arr.sort((a, b) => a-b);
// if array is reduced to a member and still no match, return false
if ((arr.length == 1) && (arr[0] !== dst))
return false;
// define a middlebound
var middlebound = Math.floor(arr.length / 2);
// if it matches right away, return true
if (dst == arr[middlebound])
return true;
// if the dst value is less than the middle value
if (dst < arr[middlebound]) {
// half the array to the first half
let lowerbound = 0;
let upperbound = middlebound;
return search(dst, arr.slice(lowerbound, upperbound));
}
// if the dst value is more than the middle value
if (dst > arr[middlebound-1]) {
// half the array to the last half
let lowerbound = middlebound;
let upperbound = arr.length;
return search(dst, arr.slice(lowerbound, upperbound));
}
}
// test it out...
var dst = 90;
var nums = [1, 2, 6, 10, 90, 53, 12, 8, 78, 4];
var included = search(dst, nums);
console.log(included); // -> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment