Watch binary search halve a sorted array until it finds the target. Worked example on 10 values, type your own array and target, and see why it is O(log n).
About this algorithm
Binary search finds a value in a sorted array by looking at the middle item and throwing away the half that cannot contain the target. Each look halves what is left, so it runs in O(log n) time: even a million items need only about 20 looks. It only works because the array is sorted.
Use binary search when the data is sorted and you will search it more than once: looking up a word in a dictionary file, finding a timestamp in a log, checking membership in a sorted list of IDs. For unsorted data or a single lookup, linear search is simpler and sorting first is not worth it. The same halving idea also works on answers rather than arrays: the Koko eating bananas page searches over eating speeds, and the rotated array page handles a sorted array that has been turned around a pivot.
low = 0 and high = n - 1. The target, if present, is somewhere between them.
mid = floor((low + high) / 2). If array[mid] equals the target, return mid.
If array[mid] is smaller than the target, everything from low to mid is too small as well, so set low = mid + 1. If it is larger, everything from mid to high is too big, so set high = mid - 1.
Repeat while low <= high. When low passes high, no position is left that could hold the target: return -1.
The page rolls a fresh sorted row of 10 numbers and targets the value at index 6, one past the middle, so both bounds have to move. Take [3, 7, 11, 15, 19, 23, 27, 31, 35, 39] and target 27. Look 1: mid = 4, 19 < 27, so low = 5. Look 2: mid = 7, 31 > 27, so high = 6. Look 3: mid = 5, 23 < 27, so low = 6. Look 4: mid = 6, and 27 is found. Four looks against seven checks for linear search on the same row. With 10 values binary search never needs more than 4 looks, since halving 10 four times leaves nothing.
A random row can repeat a value. Plain binary search returns whichever copy it lands on, not necessarily the first. To get the first copy, keep searching left after a match (high = mid - 1) and remember the last match; that version is often called lower bound.
In Java or C++ with fixed-size integers, low + high can overflow on very large arrays. Writing mid = low + (high - low) / 2 gives the same value without that risk.
Time: every look halves the range, and n can only be halved about log2(n) times before it reaches zero. Space: the loop keeps three indices; a recursive version would use O(log n) call stack instead.