- Why binary search requires sorted input โ and what happens if you forget
- How
low,high, andmiddivide-and-conquer in a singlewhileloop - Why the loop is O(log n) and how 1,000,000 elements are searched in about 20 steps
- How to avoid the classic
(low + high) / 2integer overflow bug - Why the loop condition
low <= highmatters โ and notlow < high
How Binary Search Works
Binary search is the "guess the number" game. Someone thinks of a number between 1 and 100. You guess 50. They say "higher." You guess 75. "Lower." You guess 62. In three guesses, you've narrowed the range from 100 to about 12. Binary search works the same way: each iteration eliminates half the remaining search space.
The algorithm maintains three indices: low (the left edge of the search range), high (the right edge), and mid (the middle). Initially low = 0 and high = n - 1, covering the entire array. In each iteration, compute mid, compare arr[mid] to the target, and narrow the range:
- If
arr[mid] == target: found it โ returnmid. - If
arr[mid] < target: the target must be to the right, so setlow = mid + 1. - If
arr[mid] > target: the target must be to the left, so sethigh = mid - 1.
Repeat until either the target is found or low > high (which means the search range is empty โ the target isn't in the array). The key insight is that binary search only works on sorted arrays. The "arr[mid] < target means go right" inference relies on the array being ordered. On unsorted data, binary search gives wrong answers silently.
One subtlety in C: writing mid = (low + high) / 2 is the textbook formula, but it overflows for very large arrays. If low and high are both close to INT_MAX, their sum overflows to a negative number, and mid becomes garbage. The safe form is mid = low + (high - low) / 2, which computes the same value without overflow. This bug famously lived in Java's standard library for nine years before being fixed in 2006.
๐ก In one line: each iteration halves the search range by comparing arr[mid] to the target; after at most โlogโ nโ iterations, either the target is found or the range is empty.
The Halving Algorithm
In pseudocode, iterative binary search is eight lines:
low = 0
high = n - 1
while low <= high:
mid = low + (high - low) / 2
if arr[mid] == key:
return mid
else if arr[mid] < key:
low = mid + 1
else:
high = mid - 1
return -1
The loop continues as long as low <= high. When low > high, the search range is empty โ every possible position has been checked, and the target isn't there. Returning -1 signals "not found." Compare this to linear search, which checks positions one by one and runs in O(n) time. Binary search runs in O(log n), which is exponentially faster for large arrays.
| Array size n | Linear search (worst case) | Binary search (worst case) | Speedup |
|---|---|---|---|
| 10 | 10 comparisons | 4 | 2.5ร |
| 100 | 100 | 7 | 14ร |
| 1,000 | 1,000 | 10 | 100ร |
| 1,000,000 | 1,000,000 | 20 | 50,000ร |
| 1,000,000,000 | 1,000,000,000 | 30 | 33,000,000ร |
Each additional digit of array size costs about 3.3 more comparisons. That's why binary search is the standard way to search large sorted arrays in every database, every file system, and every binary tree implementation. It's one of the most important algorithms in computer science.
Complete C Program
Program: iterative binary search using a while loop
#include <stdio.h>
int main(void) {
int n, key;
printf("Enter the number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0) {
printf("Invalid size.\n");
return 1;
}
int arr[n];
printf("Enter %d sorted integers (ascending):\n", n);
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Enter the value to search: ");
scanf("%d", &key);
int low = 0, high = n - 1, mid, result = -1;
while (low <= high) {
mid = low + (high - low) / 2; /* safe form */
if (arr[mid] == key) {
result = mid;
break;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (result == -1)
printf("Element %d not found.\n", key);
else
printf("Element %d found at index %d (0-based).\n", key, result);
return 0;
}
And here's a variant that sorts the array first with a simple bubble sort, so it works even if the user enters unsorted data. Useful for understanding the sorted-input requirement:
Variant with input sorting (educational)
#include <stdio.h>
int main(void) {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[100];
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
/* Bubble sort โ ensures sorted input for binary search */
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = t;
}
}
}
printf("Sorted array: ");
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
int key;
printf("Enter the value to search: ");
scanf("%d", &key);
int low = 0, high = n - 1, result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) { result = mid; break; }
else if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
if (result == -1) printf("Element %d not found.\n", key);
else printf("Element %d found at index %d.\n", key, result);
return 0;
}
The first version is the one to submit for the assignment โ it assumes the user enters a sorted array, as the problem statement specifies. The second version is useful when you're learning or testing: it makes the sorted-array requirement explicit by sorting first and printing the sorted order. Note that the sort costs O(nยฒ) for bubble sort, which dwarfs the O(log n) search โ real applications sort once and then do many searches.
Program Output
Enter the number of elements: 8
Enter 8 sorted integers (ascending):
10 20 30 40 50 60 70 80
Enter the value to search: 40
Element 40 found at index 3 (0-based).
Try a few more. Input a value that's not in the array, like 25, and you should get "not found". Try the first element (10, found at index 0) and the last (80, found at index 7). Try an empty array (n = 0) โ the program rejects it. Try a single-element array โ the loop runs once and either finds it or doesn't.
Enter the number of elements: 8
Enter 8 sorted integers (ascending):
10 20 30 40 50 60 70 80
Enter the value to search: 25
Element 25 not found.
Step-by-Step Explanation
Let's walk through searching for 40 in [10, 20, 30, 40, 50, 60, 70, 80].
1. Setup
low = 0, high = 7 (n โ 1). The search range is the entire array. result = -1 to start; it becomes mid when the key is found.
2. Iteration 1
mid = 0 + (7 โ 0) / 2 = 3. arr[3] = 40. That's the key โ found at index 3. result = 3, break out of the loop. Print "found at index 3."
3. A harder example: searching for 70
Same array, key = 70.
- Iteration 1: low = 0, high = 7, mid = 3. arr[3] = 40 < 70, so low = 4.
- Iteration 2: low = 4, high = 7, mid = 4 + (7 โ 4)/2 = 5. arr[5] = 60 < 70, so low = 6.
- Iteration 3: low = 6, high = 7, mid = 6 + (7 โ 6)/2 = 6. arr[6] = 70. Found at index 6.
Three iterations to search an 8-element array โ exactly โlogโ(8)โ + 1 = 4 upper bound, and we got lucky at 3. For an array of 1,000,000 elements, the worst case is 20 iterations. That's the exponential speedup of halving.
4. What happens when the key isn't found
Search for 25 in the same array. Key = 25.
- Iteration 1: low = 0, high = 7, mid = 3. arr[3] = 40 > 25, so high = 2.
- Iteration 2: low = 0, high = 2, mid = 1. arr[1] = 20 < 25, so low = 2.
- Iteration 3: low = 2, high = 2, mid = 2. arr[2] = 30 > 25, so high = 1.
- Now low = 2, high = 1. Condition
low <= highis false โ loop exits. resultis still โ1, so print "not found."
Notice that in the final iteration, low and high crossed over. That crossover is the loop termination signal: the search range is empty, meaning there's no index left where the target could be.
5. Why low <= high and not low < high
When low == high, there's still one element in the range โ the one at index low. The loop body must run once more to check that element. If the loop condition were low < high, the loop would exit before checking the last candidate. That's a classic off-by-one bug. The correct condition is low <= high.
6. Why mid = low + (high โ low) / 2
For ordinary array sizes, mid = (low + high) / 2 works fine. The overflow bug only manifests when low + high exceeds INT_MAX (about 2.1 ร 10โน). That requires an array with more than 2 billion elements โ but that's not impossible, and the bug is silent and ugly. low + (high โ low) / 2 computes the same value for all low <= high without overflow, because high โ low is non-negative and bounded by high, so the addition low + (high โ low) / 2 is always between low and high. It's the recommended form.
7. Why the loop is O(log n)
Each iteration halves the search range. Starting with size n, after k iterations the range is n / 2แต. The loop exits when the range becomes empty, i.e., when k โ logโ(n). So the loop runs at most โlogโ(n)โ + 1 times. For n = 1,000,000, that's 20 iterations. For n = 10โน, that's 30 iterations. For n = 10ยนโธ (larger than any practical array), that's 60. That's why binary search is the standard search algorithm for large sorted datasets.
๐ฏ Remember this: sorted array required; low <= high not <; mid = low + (high โ low)/2 not (low + high)/2; return mid on hit, low = mid + 1 or high = mid โ 1 on miss; โ1 when the loop exits. The whole thing is O(log n).
Frequently Asked Questions
1. What happens if I binary-search an unsorted array?
It gives wrong answers โ possibly finding the wrong element, possibly not finding elements that are present, possibly going into an infinite loop if the array is badly disordered. Binary search relies on the invariant that the target is in one specific half based on a single comparison, which is only true if the array is sorted. There's no error message, no crash โ just silently wrong results. Always sort first.
2. What's the difference between iterative and recursive binary search?
The algorithm is identical, but recursive uses O(log n) stack space for the call frames, while iterative uses O(1) space. Both are O(log n) time. Iterative is generally preferred in production because it avoids stack overflow on very large arrays and has less overhead per call. The assignment asks for iterative, which is also arguably easier to reason about.
3. Why does the loop condition use low <= high?
Because the search range is inclusive of both endpoints. When low == high, there's still one element to check. If the loop used low < high, it would exit before checking that element โ a classic off-by-one bug. You'd find the target in most cases but miss it when it happens to be the last unchecked element.
4. Why use low + (high โ low) / 2 instead of (low + high) / 2?
Integer overflow. If low and high are both close to INT_MAX, low + high overflows to a negative number, and mid becomes garbage. This requires arrays larger than about 2 billion elements, but the bug is real โ it lived in Java's standard library for nine years before being fixed. The safe form low + (high โ low) / 2 computes the same value without overflow, and it costs nothing extra.
5. Why is binary search O(log n) and not O(n)?
Because each iteration halves the search range. After k iterations, the range has size n / 2แต. The loop exits when the range is empty, i.e., when n / 2แต โ 1, so k โ logโ(n). That's the log factor. Linear search, in contrast, checks every element one by one and runs in n iterations. For n = 10โถ, binary search does 20 comparisons; linear search does 1,000,000 โ a 50,000ร speedup.
6. Why use int arr[n] (a VLA) instead of a fixed-size array?
Variable-length arrays (VLAs) were added in C99 and allow an array sized at runtime, which is natural here since the user provides n. However, VLAs are optional in C11 and later standards โ some compilers (especially MSVC) don't support them. For maximum portability, use a fixed-size array with a compile-time maximum, or allocate dynamically with malloc. For this assignment, the VLA version is fine with GCC and Clang, which are the most common teaching compilers.
๐ก Tip: After this program, try the recursive version โ the algorithm is identical, but the while loop becomes a function call. Then try finding the first occurrence of a duplicate key (instead of any occurrence), which requires continuing the search after a hit rather than breaking. That variation is called "lower bound" binary search and appears frequently in coding interviews.