Created
July 2, 2019 14:57
-
-
Save verdi327/3002123d17bb0bb37055072b48c3dd43 to your computer and use it in GitHub Desktop.
binary-search-recursive.js
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(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