- How to implement binary search using
low,high, andmidpointers - Why binary search works only when the array is sorted
- How to calculate the middle pointer using
low + (high - low) / 2 - How to recover an array index from a pointer using pointer subtraction
- Why binary search has O(log n) time complexity
- How to avoid the common integer-overflow mistake while finding the middle position
How Pointer-Based Binary Search Works
Binary search is an efficient searching technique used only on a sorted array. Instead of checking every element one by one, it repeatedly compares the key with the middle element. If the key matches the middle element, the search ends. If the key is smaller, the search continues in the left half; if it is larger, the search continues in the right half.
In the pointer version, we use three pointers: low, high, and mid. The low pointer marks the beginning of the current search range, while high marks its end. The mid pointer points to the middle element of that range. After every comparison, one half of the range is discarded.
The middle pointer is calculated as mid = low + (high - low) / 2. This is safer than writing (low + high) / 2, because adding two large pointers or indexes directly can cause overflow. The expression high - low gives the number of elements between the two pointers, dividing it by 2 gives the offset, and adding that offset to low gives the middle position.
💡 In one line: Keep low and high pointers at the current search boundaries, compare the key with *mid, and repeatedly discard the half that cannot contain the key.
The Three Steps of Binary Search
| Step | Pointer operation | Effect |
|---|---|---|
| 1. Set the search boundaries | low = arr; and high = arr + n - 1; | low points to the first element and high points to the last element |
| 2. Find and compare the middle element | mid = low + (high - low) / 2; | The key is compared with *mid to decide the next half |
| 3. Reduce the search range | low = mid + 1; or high = mid - 1; | Half of the remaining elements are discarded in each step |
Binary search depends completely on the sorted order of the array. If the array is sorted in ascending order, then every element to the left of mid is smaller than or equal to *mid, and every element to the right is greater than or equal to *mid. This ordering allows the algorithm to decide safely which half to keep and which half to discard.
If the array is not sorted, binary search may return the wrong result or fail to find an element that is actually present. Therefore, before applying binary search, the array must be arranged in ascending or descending order. In this program, we assume that the user enters the elements in ascending order.
Complete C Program
Program: binary search in a sorted array using pointers
#include <stdio.h>
#define MAX 100
/* Binary search using pointers.
Returns the index of key, or -1 if not found. */
int binary_search(const int *arr, int n, int key) {
const int *low = arr; /* first element */
const int *high = arr + n - 1; /* last element */
const int *mid;
while (low <= high) {
mid = low + (high - low) / 2; /* middle pointer */
if (*mid == key) {
return (int)(mid - arr); /* pointer subtraction gives index */
}
else if (*mid < key) {
low = mid + 1; /* search right half */
}
else {
high = mid - 1; /* search left half */
}
}
return -1; /* not found */
}
int main(void) {
int arr[MAX];
int n, key, i, result;
printf("How many elements? ");
if (scanf("%d", &n) != 1 || n <= 0 || n > MAX) {
printf("Invalid size.\n");
return 1;
}
printf("Enter %d integers in ascending order:\n", n);
for (i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1) {
printf("Invalid input.\n");
return 1;
}
}
printf("Enter the key to search: ");
if (scanf("%d", &key) != 1) {
printf("Invalid key.\n");
return 1;
}
result = binary_search(arr, n, key);
if (result == -1) {
printf("\n%d was not found in the array.\n", key);
} else {
printf("\n%d was found at index %d (position %d).\n",
key, result, result + 1);
}
return 0;
}
Program Output
How many elements? 7
Enter 7 integers in ascending order:
10 20 30 40 50 60 70
Enter the key to search: 50
50 was found at index 4 (position 5).
A second run, with a key that is not present:
How many elements? 7
Enter 7 integers in ascending order:
10 20 30 40 50 60 70
Enter the key to search: 55
55 was not found in the array.
In the first run, the middle element is checked first. Since 50 is greater than the first middle value, the search moves to the right half. It then finds 50 at index 4. In the second run, the search range keeps shrinking until low becomes greater than high, so the function returns -1.
Step-by-Step Explanation
Let us understand how the pointers move during binary search.
1. The function signature
binary_search(const int *arr, int n, int key) receives a pointer to the first element, the number of elements, and the key to search. The const keyword tells the compiler that the function will only read the array and will not modify it.
2. Setting the low and high pointers
const int *low = arr; makes low point to the first element. const int *high = arr + n - 1; makes high point to the last element. Initially, the complete array is the search range.
3. Calculating the middle pointer
mid = low + (high - low) / 2; calculates the middle position safely. Here, high - low gives the number of elements between the two pointers. Dividing it by 2 gives the offset from low, and adding that offset to low gives the middle pointer.
4. Comparing the middle element
*mid gives the value stored at the middle position. If *mid == key, the element is found. The function returns (int)(mid - arr), which gives the index of the matching element.
5. Searching the right half
If *mid < key, the key must be on the right side of the middle element because the array is sorted in ascending order. Therefore, low is moved to mid + 1, and the left half is discarded.
6. Searching the left half
If *mid > key, the key must be on the left side of the middle element. Therefore, high is moved to mid - 1, and the right half is discarded.
7. Loop termination
The loop runs while low <= high. When low becomes greater than high, the search range is empty. This means the key is not present in the array, so the function returns -1.
8. Example trace
For the sorted array [10, 20, 30, 40, 50, 60, 70] and key = 50:
- First iteration:
lowpoints to index 0,highpoints to index 6, andmidpoints to index 3. Since*mid = 40and40 < 50, movelowto index 4. - Second iteration:
lowpoints to index 4 andhighpoints to index 6. Nowmidpoints to index 5. Since*mid = 60and60 > 50, movehighto index 4. - Third iteration:
lowandhighboth point to index 4. Nowmidalso points to index 4. Since*mid = 50, the key is found and the function returns 4.
9. Why the array must be sorted
Binary search can discard half of the array only because the elements are arranged in order. If the array is unsorted, a value smaller than the middle element may still appear on the right side, so the algorithm cannot safely decide which half to discard.
10. Pointer version vs index version
The same algorithm can also be written using integer indexes:
int binary_search_index(const int arr[], int n, int key) {
int low = 0, high = n - 1, mid;
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;
}
Both versions follow the same logic. The pointer version uses low, high, and mid as pointers, while the index version uses them as integer positions. The pointer version is useful for practicing pointer arithmetic, pointer subtraction, and pointer comparison.
11. Complexity summary
Time complexity is O(log n), because the search range is divided into half after every comparison. Best case is O(1), when the key is found at the middle position in the first comparison. Worst case is O(log n), when the key is found at the last possible step or is not present. Space complexity is O(1), because the iterative version uses only a few pointer variables.
🎯 Remember this: Binary search works only on a sorted array. Use low and high pointers for the search range, calculate mid = low + (high - low) / 2, and move low or high depending on whether the key is greater or smaller than *mid.
Frequently Asked Questions
1. Why does binary search require a sorted array?
Binary search decides whether to search the left or right half by comparing the key with the middle element. This decision is valid only when the array is sorted. In an unsorted array, the key may appear on either side of the middle element, so the algorithm cannot safely discard any half.
2. What does mid - arr return?
mid - arr returns the number of elements between the first element and the middle element. Since arr points to index 0, this difference is exactly the index of the middle element. For example, if mid points to the fifth element, mid - arr is 4.
3. Why is mid = low + (high - low) / 2 better than (low + high) / 2?
The expression low + (high - low) / 2 avoids overflow. If low and high are very large, adding them directly in (low + high) / 2 may exceed the maximum value that an integer can store. The safer form first calculates the difference, which is always smaller, and then adds half of it to low.
4. What happens if the array contains duplicate elements?
This program returns the index of one matching element, but not necessarily the first or last occurrence. If the array contains duplicates and you need the first occurrence, continue searching the left half even after finding a match. To find the last occurrence, continue searching the right half.
5. Can binary search be used on a descending array?
Yes, but the comparison logic must be reversed. In a descending array, if the key is greater than the middle element, search the left half; if the key is smaller, search the right half. The array must still be consistently sorted.
6. What is the time complexity of binary search?
The time complexity is O(log n), because each comparison removes half of the remaining elements. For an array of 1,000 elements, binary search needs at most about 10 comparisons. Its space complexity is O(1) for the iterative implementation because it uses only a fixed number of pointer variables.
💡 Tip: After implementing this program, try modifying it to find the first occurrence of a duplicate key, or write a recursive version using low and high pointers. Both variations strengthen your understanding of pointer-based searching.