Skip to content

Instantly share code, notes, and snippets.

@dev-sampsonorson
Created February 10, 2022 18:23
Show Gist options
  • Save dev-sampsonorson/6030a42afe00be47f95eea894ec730cd to your computer and use it in GitHub Desktop.
Save dev-sampsonorson/6030a42afe00be47f95eea894ec730cd to your computer and use it in GitHub Desktop.
Recursive implementation of binary search
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