Binary search
Easy TimeO(log n) SpaceO(1)
Given an array arr sorted in ascending order and a target, return the index where the target sits, or -1 when it is not there. If the target appears more than once, any of its indices will do, and an empty array holds nothing so the answer is -1.
Examples
Example 1
- Input
- arr = [1, 3, 5, 7, 9, 11, 13]target = 9
- Output
- Counting from 0, the 9 in
4[1, 3, 5, 7, 9, 11, 13]sits at index 4.
Example 2
- Input
- arr = [1, 3, 5, 7, 9, 11, 13]target = 4
- Output
- The array holds only odd values, so 4 is absent.
-1
The Code
function binarySearch(arr, target) {
let lo = 0;
let hi = arr.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
binarySearch([1, 3, 5, 7, 9, 11, 13], 9);Done
More like this
All searching examples (8) →- Linear search Scan left to right until you find the value.
- Rotated search Binary search where one half is always sorted — use it.
- Find peak Climb toward the higher neighbour — a peak must lie that way.
- Binary search (recursive) The same halving, written as a call tree instead of a loop.
- Insert position Binary search that returns where a value *would* go.
- Search on the answer Binary search the answer space, not the array.