🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Binary Search in C
Learn how binary search in C finds a value in a sorted array by throwing away half the data on every step. Part of our free C programming course for embedded systems.
Binary search in C is the fastest everyday way to look up a value in a sorted array. Instead of walking through every element like linear search, it checks the middle element, decides which half can still contain the value, and discards the other half. This lecture is part of our free C programming course and our free embedded C course, so every idea is explained with a hand trace first and a small program second.
If you are preparing for embedded firmware interviews, this is one of the first algorithms you must be able to trace on paper. Lookup tables for sensors, sorted register maps and calibration data all depend on it. By the end of this free C tutorial you will be able to predict every value of low, high and mid without running the code.
What You Will Learn
- What binary search in C is and why the array must be sorted first
- The roles of
low,highandmid(some books call themlow,upandmid) - How to trace a successful search, probe by probe
- Why the search stops with an unsuccessful result when
lowbecomes greater thanhigh - How many comparisons binary search needs, compared with linear search
- Where binary search is used in embedded C programming
Prerequisites
- One-dimensional arrays: declaration, indexing, and looping over elements (earlier lectures in this chapter)
- The
whileloop andif / else if / elsefrom the Control Statements chapter - Linear search from the previous array lectures, so you can compare the two methods
- A C compiler such as
gccon Linux or any embedded toolchain that accepts C99 or later
What Is Binary Search in C?
Think about finding a word in a printed dictionary. You never start at page one. You open the book near the middle, see whether your word comes before or after that page, and repeat on the half that is left. Binary search in C does exactly this on an array.
The method has one strict requirement: the data must already be sorted (here, in ascending order). Sorting is what makes the decision at the middle element meaningful. If the middle value is smaller than your key, every element on its left is smaller still, so none of them can match.
Warning: Running binary search on an unsorted array does not crash. It silently returns wrong answers, which is much worse. Sorting algorithms such as selection sort and bubble sort, covered in the next lectures, exist partly to prepare data for this search.
Linear Search vs Binary Search
| Property | Linear search | Binary search |
|---|---|---|
| Needs sorted data | No | Yes |
| Idea | Check elements one by one | Halve the search range every step |
| Worst-case comparisons for n elements | n | about log2(n) + 1 |
| Extra memory | None | None (three int variables) |
| Best used when | Small or unsorted data | Large, sorted, read-mostly data |
The Three Index Variables: low, high and mid
The whole algorithm is controlled by three integers. They are indexes, not values.
low: the first index that can still hold the key. It starts at0.high: the last index that can still hold the key. It starts atn - 1.mid: the index we inspect right now, calculated aslow + (high - low) / 2.
Every pass of the loop compares the key with data[mid] and takes exactly one of three decisions.
| Comparison | Meaning | Action |
|---|---|---|
| key == data[mid] | Found it | Stop and report mid |
| key < data[mid] | Key can only be on the left | high = mid - 1 |
| key > data[mid] | Key can only be on the right | low = mid + 1 |
The loop runs while low <= high. As soon as low becomes larger than high, the range is empty and the key is not in the array.
Binary Search in C: A Successful Search Step by Step
We will use this sorted array of ten values for the whole lecture. The indexes run from 0 to 9.
Our key is 35. Before the first probe, the whole array is in play: low = 0, high = 9, so mid = 0 + (9 - 0) / 2 = 4.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| value | 3 | 8 | 14 | 21 | 27 | 35 | 42 | 56 | 63 | 71 |
| pointer | low | mid | high |
The key 35 is greater than 27, so everything from index 0 to 4 is useless. We set low = mid + 1 = 5.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| value | 3 | 8 | 14 | 21 | 27 | 35 | 42 | 56 | 63 | 71 |
| pointer | low | mid | high |
Now 35 is smaller than 56, so the right part is gone. We set high = mid - 1 = 6. Only two candidates remain: indexes 5 and 6.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| value | 3 | 8 | 14 | 21 | 27 | 35 | 42 | 56 | 63 | 71 |
| pointer | low, mid | high |
With mid = 5 + (6 - 5) / 2 = 5 the element matches. Three probes were enough to search ten elements. Linear search would have needed six comparisons for the same key.
When Binary Search in C Fails: low Passes high
A search is unsuccessful when the key is not stored in the array. Let us look for 30, a value that sits between 27 and 35. The first two probes are identical to the previous search, because 30 is also greater than 27 and smaller than 56.
| Step | low | high | mid | data[mid] | Comparison | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 9 | 4 | 27 | 30 > 27 | low = mid + 1 = 5 |
| 2 | 5 | 9 | 7 | 56 | 30 < 56 | high = mid – 1 = 6 |
| 3 | 5 | 6 | 5 | 35 | 30 < 35 | high = mid – 1 = 4 |
| stop | 5 | 4 | – | – | low > high | Key not found |
After step 3 the two pointers have crossed: low is 5 and high is 4. The picture below shows why nothing is left to search.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| value | 3 | 8 | 14 | 21 | 27 | 35 | 42 | 56 | 63 | 71 |
| pointer | high | low |
Key idea
The condition low <= high means “the range still contains at least one index”. When it becomes false, the range is empty. That is the only way an unsuccessful search ends, so you never need a separate “not found” counter.
Binary Search in C: Tracing Program and Output
The following program prints the same trace you just followed by hand. It does not read input, so you can compile and run it immediately. Save it as ep_bsearch_trace.c.
#include <stdio.h>
int main(void)
{
const int data[10] = {3, 8, 14, 21, 27, 35, 42, 56, 63, 71};
const int key_list[2] = {35, 30};
for (int k = 0; k < 2; k++) {
int key = key_list[k];
int low = 0;
int high = 9;
int found = -1;
int step = 1;
printf("Searching for %d\n", key);
while (low <= high) {
int mid = low + (high - low) / 2;
printf(" step %d: low=%d high=%d mid=%d data[mid]=%d\n",
step++, low, high, mid, data[mid]);
if (data[mid] == key) {
found = mid;
break;
} else if (key < data[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
if (found >= 0)
printf(" -> %d found at index %d\n", key, found);
else
printf(" -> %d not found (low=%d, high=%d)\n", key, low, high);
}
return 0;
}
Build and run it:
gcc -std=c17 -Wall -Wextra -o ep_bsearch_trace ep_bsearch_trace.c
./ep_bsearch_trace
Expected output:
Searching for 35
step 1: low=0 high=9 mid=4 data[mid]=27
step 2: low=5 high=9 mid=7 data[mid]=56
step 3: low=5 high=6 mid=5 data[mid]=35
-> 35 found at index 5
Searching for 30
step 1: low=0 high=9 mid=4 data[mid]=27
step 2: low=5 high=9 mid=7 data[mid]=56
step 3: low=5 high=6 mid=5 data[mid]=35
-> 30 not found (low=5, high=4)
Notice that the loop condition is checked before mid is used. A common beginner version of this program reads arr[mid] in the while condition before mid has ever been assigned, which is undefined behaviour. Here mid is created inside the loop body, so it always holds a valid value.
Programs that report positions the way people count (first element is position 1) simply print found + 1. The index stays zero-based inside the algorithm.
Why Binary Search Is So Fast
Each probe removes at least half of the remaining elements. After k probes at most n / 2k elements are left, so the number of probes is about log2(n) + 1 in the worst case. Doubling the array size adds only one extra probe.
| Elements (n) | Linear search worst case | Binary search worst case |
|---|---|---|
| 10 | 10 | 4 |
| 100 | 100 | 7 |
| 1,000 | 1,000 | 10 |
| 10,000 | 10,000 | 14 |
| 1,000,000 | 1,000,000 | 20 |
Binary Search in Embedded C Programming
For anyone following a free embedded systems course, binary search matters for practical reasons beyond speed:
- Constant, predictable time. The worst case is known in advance, which suits real-time code with tight deadlines.
- No dynamic memory. Only three integers are needed, so it works on microcontrollers with a few kilobytes of RAM.
- Tables live in flash. Sorted calibration tables, thermistor curves and command-code lists can be declared
constand searched in place. - Protocol handling. Message IDs, CAN identifiers and register addresses are often kept sorted so a firmware parser can find a handler quickly.
Common Mistakes and Troubleshooting
| Mistake | What happens | Fix |
|---|---|---|
| Searching unsorted data | Wrong or missing results | Sort first, or use linear search |
Using low < high as the loop condition | The last remaining element is never checked | Use low <= high |
Setting low = mid instead of mid + 1 | Infinite loop when two elements remain | Always move past mid |
Reading data[mid] before assigning mid | Undefined behaviour | Calculate mid inside the loop |
| Confusing index with position | Off-by-one in printed messages | Print index + 1 only when reporting to humans |
Best Practices
- Write
mid = low + (high - low) / 2. The shorter form(low + high) / 2can overflow a 16-bitinton small microcontrollers when the array is large. - Return the index, or
-1when not found, from a dedicated function so the logic is written once. - Security and safety: never use a key or index that comes from outside the device (UART, network) without checking that it is inside the array bounds.
- Declare read-only tables as
constso the linker can place them in flash and save RAM. - Test three cases every time: first element, last element, and a value that is missing.
Summary and Key Takeaways
- Binary search in C needs a sorted array and repeatedly inspects the middle element.
- Three outcomes per probe: match, move
highleft, or movelowright. - The search fails exactly when
lowbecomes greater thanhigh. - Worst-case probes grow as log2(n), so even a million elements need only about 20 probes.
- Use
low + (high - low) / 2to avoid integer overflow.
Conclusion
You now understand binary search in C well enough to trace it on paper for any sorted array, successful or not. The next lecture turns the loop into a reusable function, measures probe counts, and applies the idea to an embedded ADC lookup table. It is a good moment to re-run the tracing program with your own sorted values and predict the output before you press Enter. This kind of habit is what a good free C programming course should build.
Frequently Asked Questions
Does binary search in C work on unsorted arrays?
No. The decision at each step relies on the order of the data. Sort the array first or use linear search.
What is the time complexity of binary search?
O(log n) in the worst and average case, and O(1) in the best case when the first probe matches.
Why is mid calculated as low + (high – low) / 2?
It gives the same result as (low + high) / 2 but never overflows, which matters on 8-bit and 16-bit embedded targets.
What if the array contains duplicate values?
The basic version returns one matching index, not necessarily the first. A lower-bound variant, shown in the next lecture, finds the first match.
How do I know the search was unsuccessful?
The loop ends because low is greater than high without ever hitting a match, so the function returns -1.
Can I use binary search on a linked list?
It is not practical, because reaching the middle node needs a walk through the list. Binary search needs fast index access, which arrays provide.
Is binary search used in embedded firmware?
Yes. Sorted lookup tables in flash, message ID tables and calibration curves are classic uses.
Keep Learning with the Free C Course
Continue with the binary search program, then move on to sorting. Every lecture is part of our free embedded C programming course.

2 Comments