The iterative form uses a loop and two indexes, so it needs only O(1) extra space and cannot overflow the stack. Wrap it in a function that returns the index or -1. A lower-bound variant uses a half-open range [lo, hi) and returns the first position where a[pos] >= key, which finds the first duplicate or the insertion point.
Remember
/* lower bound: first index with a[i] >= key */
lo = 0; hi = n;
while (lo < hi) {
mid = lo + (hi - lo) / 2;
if (a[mid] < key) lo = mid + 1; else hi = mid;
}
return lo;
Reference
Cheat Sheet
Keep these facts handy while you work with Iterative Binary Search in C in C.
#include <stdio.h>
static int bsearch_int(const int a[], int n, int key) {
int lo = 0, hi = n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == key) return mid;
if (a[mid] < key) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
int main(void) {
int a[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
printf("72 -> %d\n", bsearch_int(a, 10, 72));
printf("1 -> %d\n", bsearch_int(a, 10, 1));
printf("91 -> %d\n", bsearch_int(a, 10, 91));
return 0;
}
Output
72 -> 8
1 -> -1
91 -> 9
How It Works
72: midpoints 4 (16), 7 (56), then 8 (72).
1 is smaller than everything, so the range shrinks to empty and -1 is returned.
91 is the last element and is found at index 9.
Example 2 — Lower bound for duplicates and insertion
Find the first 2 and the insertion point for 4.
C
#include <stdio.h>
static int lower_bound(const int a[], int n, int key) {
int lo = 0, hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] < key) lo = mid + 1;
else hi = mid;
}
return lo;
}
int main(void) {
int a[] = {1, 2, 2, 2, 3};
printf("first 2 at index %d\n", lower_bound(a, 5, 2));
printf("insert position for 4: %d\n", lower_bound(a, 5, 4));
return 0;
}
Output
first 2 at index 1
insert position for 4: 5
How It Works
The range shrinks toward the leftmost element that is not smaller than the key.
For 2 that is index 1, the first of three duplicates.
For 4 every element is smaller, so the position is the end, 5.
Edge Cases & Pitfalls
Check these before relying on Iterative Binary Search in C in real programs.
mix
Mixing range styles
Do not combine lo <= hi with hi = mid. Choose closed or half-open consistently.
empty
Empty arrays
With n == 0 the function must return -1 (or 0 for lower bound) without reading a[0].
Remember
Key Takeaways
O(1) space.
Closed or half-open ranges.
Lower bound handles duplicates.
One line: The iterative form uses a loop and two indexes, so it needs only O(1) extra space and cannot overflow the stack.
Frequently Asked Questions
It uses constant extra space and avoids recursion overhead.
Use a lower-bound search that continues left when a[mid] >= key.
Continue with "Recursive Binary Search in C" next. Express binary search as a function that calls itself on a smaller range. The C Searching Algorithms hub lists every topic in order.