Created
July 14, 2021 05:01
-
-
Save lexcraw4d/0543a13b5b14565654d85ffe1241b399 to your computer and use it in GitHub Desktop.
Binary Search Algorithm
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
const data = [12, 23, 38, 40, 54, 62, 71, 87, 99]; | |
const binarySearch = (arr, num, left, right) => { | |
let middle = Math.floor((left + right) / 2); | |
// range overlapped, so never found number | |
if (left > right) { | |
return -1; | |
} | |
else if (num === arr[middle]) { | |
return middle; | |
} | |
else if (num < arr[middle]) { | |
// call again with a new right value | |
return binarySearch(arr, num, left, middle - 1); | |
} | |
else { | |
// call again with a new left value | |
return binarySearch(arr, num, middle + 1, right); | |
} | |
}; | |
// set initial left and right values on first call | |
console.log(binarySearch(data, 12, 0, data.length - 1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment