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 AA of nn elements, indexed from 00 to n1n-1, and the target value TT. Initialize two pointers: L=0L = 0 for the left bound and R=n1R = n-1 for the right bound.

The steps

  1. While LRL \le R, compute the middle index M=L+R2M = \lfloor \frac{L + R}{2} \rfloor. 2. If A[M]=TA[M] = T, return MM. 3. If A[M]<TA[M] < T, the target must be in the right half, so set L=M+1L = M + 1. 4. If A[M]>TA[M] > T, the target must be in the left half, so set R=M1R = M - 1. 5. If the loop terminates without returning, the target is not in the array (return 1-1).

Checking the result

Verify that A[extresult]=TA[ ext{result}] = T. If the algorithm returns 1-1, verify manually that TT does not exist between A[L]A[L] and A[R]A[R] at the point of loop termination.

Common errors

Integer overflow can occur when calculating MM using L+RL + R for very large arrays. Use M=L+RL2M = L + \lfloor \frac{R - L}{2} \rfloor instead. Off-by-one errors in loop conditions (using << instead of \le) or bounds updates (using L=ML = M instead of L=M+1L = M + 1) lead to missed elements or infinite loops.

Worked example

Find T=7T = 7 in the sorted array A=[1,3,5,7,9,11]A = [1, 3, 5, 7, 9, 11].

Initial state: n=6n = 6, L=0L = 0, R=5R = 5. Iteration 1: M=(0+5)/2=2M = \lfloor (0 + 5)/2 \rfloor = 2. A[2]=5A[2] = 5. Since 5<75 < 7, set L=2+1=3L = 2 + 1 = 3. Iteration 2: L=3L = 3, R=5R = 5. M=(3+5)/2=4M = \lfloor (3 + 5)/2 \rfloor = 4. A[4]=9A[4] = 9. Since 9>79 > 7, set R=41=3R = 4 - 1 = 3. Iteration 3: L=3L = 3, R=3R = 3. M=(3+3)/2=3M = \lfloor (3 + 3)/2 \rfloor = 3. A[3]=7A[3] = 7. Since 7=77 = 7, return M=3M = 3. The index of target 77 is 33.

FAQ

Run your own problem

References: Introduction to Algorithms (Cormen, Leiserson, Rivest, Stein) · The Algorithm Design Manual (Skiena)

See also