Binary search
A library shelf displays sorted copy numbers. Return the zero-based index of a requested number, or -1 if the copy is absent.
Examples
Last copy
Input
[3, 8, 11, 19], target = 19
Expected output
3
Missing copy
Input
[3, 8, 11, 19], target = 10
Expected output
-1
Empty shelf
Input
[], target = 3
Expected output
-1
Hints and solution
Hint 1
Compare the copy at the midpoint with the requested number.
Hint 2
Move beyond the midpoint when it cannot be the answer.
Reveal worked answer
Searching for 19 examines 8, then 11, then 19 at index 3. Searching for 10 examines 8, then 11. Both selected midpoints are discarded, leaving an empty range. An empty shelf has no candidates from the beginning.