Created
September 27, 2014 12:07
-
-
Save fudini/60a194665db571a03986 to your computer and use it in GitHub Desktop.
Binary search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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