Skip to content

Instantly share code, notes, and snippets.

@verdi327
Created July 2, 2019 14:57
Show Gist options
  • Save verdi327/3002123d17bb0bb37055072b48c3dd43 to your computer and use it in GitHub Desktop.
Save verdi327/3002123d17bb0bb37055072b48c3dd43 to your computer and use it in GitHub Desktop.
binary-search-recursive.js
function binarySearch(sortedArray, searchValue, minIndex=0, maxIndex=sortedArray.length-1) {
let currentElement, middleIndex;
while (minIndex <= maxIndex) {
// Find the value of the middle of the array
middleIndex = Math.floor((minIndex + maxIndex) / 2);
currentElement = sortedArray[middleIndex];
// It's the same as the value in the middle - we can return!
if (currentElement === searchValue) {
return middleIndex;
}
// Is the value less than the value in the middle of the array
if (currentElement < searchValue) {
return binarySearch(sortedArray, searchValue, middleIndex + 1, maxIndex);
}
// Is the value greater than the value in the middle of the array
if (currentElement > searchValue) {
return binarySearch(sortedArray, searchValue, minIndex, middleIndex - 1);
}
}
return -1;
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment