What is Binary Search in C- C Programming Course For Engineering Students

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Free C Programming Course | Arrays | Lecture 32

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, high and mid (some books call them low, up and mid)
  • How to trace a successful search, probe by probe
  • Why the search stops with an unsuccessful result when low becomes greater than high
  • 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 while loop and if / else if / else from the Control Statements chapter
  • Linear search from the previous array lectures, so you can compare the two methods
  • A C compiler such as gcc on 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

PropertyLinear searchBinary search
Needs sorted dataNoYes
IdeaCheck elements one by oneHalve the search range every step
Worst-case comparisons for n elementsnabout log2(n) + 1
Extra memoryNoneNone (three int variables)
Best used whenSmall or unsorted dataLarge, 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 at 0.
  • high: the last index that can still hold the key. It starts at n - 1.
  • mid: the index we inspect right now, calculated as low + (high - low) / 2.

Every pass of the loop compares the key with data[mid] and takes exactly one of three decisions.

ComparisonMeaningAction
key == data[mid]Found itStop and report mid
key < data[mid]Key can only be on the lefthigh = mid - 1
key > data[mid]Key can only be on the rightlow = 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.

How to read the diagrams
Grey pill: already eliminatedBlue pill: the mid element being probedPlain number: still inside low..high

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.

Probe 1: low = 0, high = 9, mid = 4, data[mid] = 27
index0123456789
value381421273542566371
pointerlowmidhigh

The key 35 is greater than 27, so everything from index 0 to 4 is useless. We set low = mid + 1 = 5.

Probe 2: low = 5, high = 9, mid = 7, data[mid] = 56
index0123456789
value381421273542566371
pointerlowmidhigh

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.

Probe 3: low = 5, high = 6, mid = 5, data[mid] = 35 (match)
index0123456789
value381421273542566371
pointerlow, midhigh

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.

Search trace for key 30
Steplowhighmiddata[mid]ComparisonAction
10942730 > 27low = mid + 1 = 5
25975630 < 56high = mid – 1 = 6
35653530 < 35high = mid – 1 = 4
stop54––low > highKey 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.

Final state: low (5) is greater than high (4), every element is eliminated
index0123456789
value381421273542566371
pointerhighlow

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 caseBinary search worst case
10104
1001007
1,0001,00010
10,00010,00014
1,000,0001,000,00020

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 const and 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

MistakeWhat happensFix
Searching unsorted dataWrong or missing resultsSort first, or use linear search
Using low < high as the loop conditionThe last remaining element is never checkedUse low <= high
Setting low = mid instead of mid + 1Infinite loop when two elements remainAlways move past mid
Reading data[mid] before assigning midUndefined behaviourCalculate mid inside the loop
Confusing index with positionOff-by-one in printed messagesPrint index + 1 only when reporting to humans

Best Practices

  • Write mid = low + (high - low) / 2. The shorter form (low + high) / 2 can overflow a 16-bit int on small microcontrollers when the array is large.
  • Return the index, or -1 when 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 const so 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 high left, or move low right.
  • The search fails exactly when low becomes greater than high.
  • Worst-case probes grow as log2(n), so even a million elements need only about 20 probes.
  • Use low + (high - low) / 2 to 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.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *