Binary Search — Definition, Formula & Example
Binary search is a method for finding a value in a sorted list. You check the middle entry and then throw away the half that cannot contain your target.
Let be a sorted array and a target. Set and . While , compute . If , return . If , set . Otherwise set . If , then is not in the array. Each pass removes and leaves at most half of the current range. So the loop runs at most times, and the running time is .
Key Formula
Where:
- = Largest possible number of comparisons with a middle entry for a sorted list of length n
- = Number of entries in the sorted list (a positive integer)
- = Floor function: round down to the nearest integer
Worked Example
Problem: The sorted list 3, 8, 12, 17, 21, 26, 30, 34, 39, 45, 51, 58, 63, 70, 77 has 15 entries in positions 1 through 15. Use binary search to find the position of 63. Count the comparisons.
Step 1: Start with the whole list, so and . The middle position is 8, and . Because , the target must lie to the right, so set .
Step 2: Now the range is positions 9 to 15. The middle is position 12, and . Because , set . The new middle is position 14, and . Because , set .
Step 3: Only position 13 remains, and . That is a match. The search used 4 comparisons, which is exactly the worst-case bound for 15 entries.
Answer: The value 63 is at position 13. Binary search found it in 4 comparisons. A left-to-right scan would have needed 13.
Why It Matters
In a discrete math or data structures course, binary search is the standard first example of the recurrence , which solves to . The gap in speed is large. A linear search through 1,000,000 sorted records may need 1,000,000 checks, but binary search needs at most 20. The same halving idea drives database indexes, the bisection method for finding roots of equations, and tools like git bisect that locate the commit where a bug first appeared.
Common Mistakes
Mistake: Running binary search on a list that is not sorted.
Correction: The method only works because sorting guarantees that everything left of the middle is smaller than everything right of it. Try searching the unsorted list 9, 2, 7, 4, 5 for 4. The middle entry is position 3, which holds 7. Since 4 < 7, the search keeps the left part {9, 2} and discards 7 and everything to its right, including the 4 at position 4. It then reports that 4 is not in the list, which is false. Sort the list first, or use a linear search.
