Created
January 14, 2014 17:09
-
-
Save motiooon/8421888 to your computer and use it in GitHub Desktop.
Binary Search
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 bSearch(items, value){ | |
var startIndex = 0; | |
var stopIndex = items.length-1; | |
var middle = Math.floor((startIndex + stopIndex)/2); | |
while(value !== items[middle] && startIndex < stopIndex){ | |
if(value > items[middle]){ | |
startIndex = middle + 1; | |
}else if(value < items[middle]){ | |
stopIndex=middle-1; | |
} | |
middle = Math.floor(( startIndex + stopIndex ) / 2); | |
} | |
return (items[middle] === value) ? middle : -1; | |
}; | |
var items = [1, 3, 7, 9, 23, 34, 45, 52, 65, 67, 76, 82, 84, 86, 92, 100, 104, 121]; | |
console.log("34 is at index: ", bSearch(items, 34)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment