Skip to content

Instantly share code, notes, and snippets.

@fudini
Created September 27, 2014 12:07
Show Gist options
  • Save fudini/60a194665db571a03986 to your computer and use it in GitHub Desktop.
Save fudini/60a194665db571a03986 to your computer and use it in GitHub Desktop.
Binary search
function split(arr) {
var l = arr.length,
m = Math.round(l / 2);
return {
left: arr.slice(0, m),
right: arr.slice(m, l)
}
}
function find(arr, el) {
if(arr.length === 1) {
if(arr[0] === el) return el;
return -1;
}
var s = split(arr);
if(s.right[0] <= el) return find(s.right, el);
return find(s.left, el);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment