Created
March 26, 2014 06:16
-
-
Save jonarnaldo/9777695 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
var newArr = [1, 2, 3, 4, 5, 6]; | |
function binarySearch(searchElement) { | |
var minIndex = 0; | |
var maxIndex = this.length - 1; | |
var currentIndex; | |
var currentElement; | |
while (minIndex <= maxIndex) { | |
currentIndex = Math.round((minIndex + maxIndex) / 2); | |
currentElement = this[currentIndex]; | |
if (currentElement < searchElement) { | |
minIndex = currentIndex + 1; | |
} else if (currentElement > searchElement) { | |
maxIndex = currentIndex - 1; | |
} else { | |
return currentIndex; | |
} | |
} | |
return ('not found'); | |
} | |
binarySearch.call(newArr, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment