How to perform binary search on a sorted array
Binary search locates a target value within a sorted array by repeatedly dividing the search interval in half. It applies exclusively to arrays or lists that are already sorted in ascending or descending order.
The setup
Define the array of elements, indexed from to , and the target value . Initialize two pointers: for the left bound and for the right bound.
The steps
- While , compute the middle index . 2. If , return . 3. If , the target must be in the right half, so set . 4. If , the target must be in the left half, so set . 5. If the loop terminates without returning, the target is not in the array (return ).
Checking the result
Verify that . If the algorithm returns , verify manually that does not exist between and at the point of loop termination.
Common errors
Integer overflow can occur when calculating using for very large arrays. Use instead. Off-by-one errors in loop conditions (using instead of ) or bounds updates (using instead of ) lead to missed elements or infinite loops.
Worked example
Find in the sorted array .
Initial state: , , . Iteration 1: . . Since , set . Iteration 2: , . . . Since , set . Iteration 3: , . . . Since , return . The index of target is .
FAQ
Run your own problem
References: Introduction to Algorithms (Cormen, Leiserson, Rivest, Stein) · The Algorithm Design Manual (Skiena)
See also