Created
November 5, 2012 11:53
-
-
Save clippit/4016851 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
var find = function(arr, key) { | |
if (arr.length < 1) { | |
return null; | |
} | |
var low = 0, | |
high = arr.length - 1, | |
middle; | |
while(high >= low) { | |
middle = Math.floor((low + high) / 2); | |
//console.log(low, middle, high); | |
value = arr[middle]; | |
if (value == key) { | |
return middle; | |
} else if (value < key) { | |
low = middle + 1; | |
} else { | |
high = middle - 1; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why not
value === key
?