Created
March 28, 2013 13:16
-
-
Save kampfer/5263055 to your computer and use it in GitHub Desktop.
binary search in javascript
This file contains 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 binarySearch(collection, start, end, target) { | |
if(start > end) { | |
return; | |
} | |
var mid = Math.floor( (start + end) / 2 ); | |
if(collection[mid] > target) { | |
return binarySearch(collection, start, mid - 1, target); | |
} | |
if(collection[mid] < target) { | |
return binarySearch(collection, mid + 1, end, target); | |
} | |
return mid; | |
} | |
var ary = [1,2,3,6,7,9,11,234,1231,3233,11111,222222]; | |
var target = 222222; | |
var index = binarySearch(ary, 0, ary.length, target); | |
console.log(index); | |
console.log(target === ary[index]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment