Iterative binary search is the standard loop-based implementation of binary search. It avoids recursion and therefore uses constant extra space. The logic maintains a shrinking interval until the target is found or the interval becomes empty.
This form is preferred in systems code because it has no call overhead and predictable control flow.
Problem
Given a sorted array of length and a value , find an index such that
If no such index exists, return .
Algorithm
Maintain two indices and that bound the current search interval.
iterative_binary_search(A, x):
l = 0
r = length(A) - 1
while l <= r:
m = l + (r - l) // 2
if A[m] == x:
return m
else if A[m] < x:
l = m + 1
else:
r = m - 1
return -1Example
Let
and
Execution:
| step | l | r | m | A[m] | action |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 6 | move right |
| 2 | 3 | 5 | 4 | 10 | found |
Return index .
Loop Invariant
At every iteration:
- If exists in , then lies within the interval
The update rules preserve this invariant while reducing the interval size.
Termination
The loop terminates when:
At this point, the interval is empty and the target does not exist.
Complexity
| case | comparisons | time |
|---|---|---|
| best | ||
| worst | ||
| average |
Space complexity:
Notes
- The midpoint is computed as
l + (r - l) // 2to avoid integer overflow in fixed-width arithmetic. - This version is tail-recursion-free and suitable for performance-critical paths.
- All binary search variants can be expressed in this iterative form by modifying the condition and update rules.
Implementation
def iterative_binary_search(a, x):
l, r = 0, len(a) - 1
while l <= r:
m = l + (r - l) // 2
if a[m] == x:
return m
elif a[m] < x:
l = m + 1
else:
r = m - 1
return -1func IterativeBinarySearch(a []int, x int) int {
l, r := 0, len(a)-1
for l <= r {
m := l + (r-l)/2
if a[m] == x {
return m
} else if a[m] < x {
l = m + 1
} else {
r = m - 1
}
}
return -1
}