Created
February 10, 2022 18:23
-
-
Save dev-sampsonorson/6030a42afe00be47f95eea894ec730cd to your computer and use it in GitHub Desktop.
Recursive implementation of 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
const input1 = [-1, 0, 1, 2, 3, 4, 7, 9, 10, 20]; | |
// 0 1 2 3 4 5 6 7 8 9 | |
const binarySearch = (array, left, right, target) => { | |
if (left > right) | |
return -1; | |
const mid = Math.floor((left + right) / 2); | |
if (target === array[mid]) | |
return mid; | |
if (target > array[mid]) | |
return binarySearch(array, mid + 1, right, target); | |
return binarySearch(array, left, mid - 1, target); | |
} | |
console.log(binarySearch(input1, 0, input1.length - 1, 7)); | |
console.log(binarySearch(input1, 0, input1.length - 1, 10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment