Binary search
MediumSearching · JavaScript
The task
Write binarySearch(arr, target) that returns the index of target in the sorted array arr, or -1 if it is not there.
Use binary search: look at the middle, then discard the half that cannot contain the target. All values are distinct.
Examples
- binarySearch([1, 3, 5, 7, 9], 7) returns 3
Your code runs in your browser, in a separate worker, and is never sent to us. Edit the function, then press Run tests. Your work is saved here as you type.
JavaScriptCtrl or Cmd + Enter to run