Binary search lower bound with a half-open range in C
Calibration tables often contain ordered values that can be searched without inspecting every entry. A boundary query is slightly different from looking for any exact match: it asks where the key could be inserted without violating ordering. That difference matters when repeated values exist or when the measured input falls between entries.
The contract
Use a candidate interval from lo inclusive to hi exclusive. At each iteration the midpoint lies inside the interval. If the value there is below the key, discard it and everything earlier; otherwise retain it as a possible boundary. Compute the midpoint from the difference between endpoints to avoid adding two potentially large indices.
A small executable example
#include <stddef.h>
#include <assert.h>
#include <stdio.h>
static size_t lower(const int *a, size_t n, int key) {
size_t lo = 0, hi = n;
while (lo < hi) {
size_t m = lo + (hi - lo) / 2;
if (a[m] < key) lo = m + 1;
else hi = m;
}
return lo;
}
int main(void) {
const int a[] = {2, 4, 4, 9};
assert(lower(a, 4, 4) == 1);
assert(lower(a, 4, 5) == 3);
assert(lower(a, 4, 10) == 4);
assert(lower(a, 0, 1) == 0);
puts("search boundaries verified");
}
search boundaries verified
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
The sorted-order precondition is essential. On a target, the values may reside in flash or a memory region requiring special read operations; the example is for ordinary C array access. Returning n is not permission to read a[n]. A caller doing an exact lookup must first ensure the returned index is below n and then compare the candidate value.
Checks to add in your own project
Test empty and singleton ranges, keys below and above the entire array, and duplicates at both boundaries. A reference linear scan can verify results for many randomly generated sorted arrays. Compare measured target latency against the requirements of the calling context. A logarithmic comparison count alone says nothing about flash wait states, caching or interrupt scheduling.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.