Maintained by Vikas Dulgunde, software engineer
You are handed an array of numbers that is guaranteed to be sorted from smallest to largest, along with a single target value to locate.
If the target sits somewhere in the array, report the index where it lives. If it never appears, report -1 instead.
Because the input is already ordered, you can do far better than scanning every element. The order lets you discard half of the remaining candidates with each comparison.
Each value in the array is distinct, so there is at most one correct index to return.
The value 9 sits at index 4, so that index is returned.
No element equals 2, so the search reports -1.
A single-element array whose only value matches the target returns index 0.
Visible test cases
A plain left-to-right scan works and is easy to get right, but it ignores the fact that the array is sorted.
Track a low and a high bound for the slice that could still contain the target, then look at the middle element of that slice.
If the middle value is too small, the answer can only be to its right; if too large, only to its left. Move the matching bound and repeat until the bounds cross.
Walk through every element and compare it to the target, ignoring the sort.
Keep a candidate window and halve it each step by comparing the target to the middle element.