Skip to content

Instantly share code, notes, and snippets.

@kevinah95
Last active April 25, 2019 18:28
Show Gist options
  • Select an option

  • Save kevinah95/1557bd9c3c63a949edcdf5b9b066608d to your computer and use it in GitHub Desktop.

Select an option

Save kevinah95/1557bd9c3c63a949edcdf5b9b066608d to your computer and use it in GitHub Desktop.
let binarySearch = (arr, left, right, searchValue) => {
if (left <= right) {
middle = Math.floor((left + (right - left) / 2))
if (searchValue === arr[middle]) {
return middle
}
if (searchValue < arr[middle]) {
return binarySearch(arr, left, middle - 1, searchValue)
} else {
return binarySearch(arr, middle + 1, right, searchValue)
}
}
return -1
}
let arr = [1, 2, 3, 4, 9]
console.log("Index of 9 element = "+binarySearch(arr, 0, arr.length - 1, 9))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment