Skip to content

Instantly share code, notes, and snippets.

@okovalov
Created February 26, 2019 12:56
Show Gist options
  • Save okovalov/72634b435c237ff0f26a43b1abd9e027 to your computer and use it in GitHub Desktop.
Save okovalov/72634b435c237ff0f26a43b1abd9e027 to your computer and use it in GitHub Desktop.
const binarySearch = (arr, key) => {
const midIdx = Math.floor(arr.length / 2)
const midElement = arr[midIdx]
if (midElement === key) return true
if (arr.length === 1) return false
if (midElement > key) {
return binarySearch(arr.splice(0, midIdx), key)
}
if (midElement < key) {
return binarySearch(arr.splice(midIdx, arr.length), key)
}
return false
}
const arr = [1, 3, 5, 6, 8, 12, 23, 55, 90, 98]
console.log(binarySearch([...arr], 91)) // false
console.log(binarySearch([...arr], 23)) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment