🔴 Advanced  ·  Lesson 41

Binary Search

What is binary search?

Suppose you look for a word in a dictionary. You do not read every page from the start — you open near the middle, see if your word is before or after, and jump. Binary search does exactly this on a sorted array, and it is dramatically faster than checking each element one by one.

The one rule: the array must be sorted first. That is what lets binary search safely throw away half the data each step.

The halving idea

Keep three markers: low, high, and the mid between them. Compare the target with the middle:

  • If it equals mid — found it.
  • If it is smaller — the answer must be in the left half, so move high down.
  • If it is larger — it must be in the right half, so move low up.

Each comparison removes half of what is left. That is the whole trick.

Iterative program

C Language
#include <stdio.h>
int binarySearch(int a[], int n, int key) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (a[mid] == key)      return mid;   // found
        else if (a[mid] < key)  low = mid + 1; // go right
        else                    high = mid - 1; // go left
    }
    return -1;                  // not found
}
int main() {
    int a[] = {10, 20, 30, 40, 50};
    int pos = binarySearch(a, 5, 40);
    if (pos != -1) printf("Found at index %d\n", pos);
    else           printf("Not found\n");
    return 0;
}
Output:
Found at index 3

Dry run

Searching for 40 in {10, 20, 30, 40, 50}:

Steplowhighmida[mid]Action
10423030 < 40 → go right
234340found at 3

Just two comparisons instead of four — and the gap grows huge as the array gets bigger.

Recursive program

C Language
int binarySearch(int a[], int low, int high, int key) {
    if (low > high) return -1;              // base case
    int mid = low + (high - low) / 2;
    if (a[mid] == key)     return mid;
    if (a[mid] < key)      return binarySearch(a, mid + 1, high, key);
    else                   return binarySearch(a, low, mid - 1, key);
}

Same logic, expressed by calling itself on the chosen half instead of looping.

Why it is so fast

Array sizeLinear search (worst)Binary search (worst)
1001007
1,0001,00010
1,000,0001,000,00020

Because each step halves the data, binary search runs in O(log n) — a million items need only about twenty checks.

Common mistakes

  • Running it on an unsorted array — the result is meaningless.
  • Using (low + high) / 2, which can overflow; prefer low + (high - low) / 2.
  • Wrong loop condition — it must be low <= high, not <.
  • Forgetting to move past mid with mid + 1 / mid - 1, causing an infinite loop.
🏋️ Practice

Search for a value that is not in the array (say 25) and confirm it returns −1. Then add a counter to print how many comparisons it took, and compare with a simple linear search.

Summary

  • Binary search finds a value in a sorted array by halving each step.
  • Compare with the middle; keep the half that could contain the target.
  • Use low + (high - low) / 2 for the middle to avoid overflow.
  • Iterative and recursive versions give the same result.
  • It runs in O(log n) — far faster than linear search on large data.

Frequently Asked Questions

What is binary search in C?
Binary search is a fast way to find a value in a sorted array. It looks at the middle element, and because the array is sorted it can throw away half the array in one step — repeating this until it finds the value or runs out of elements. It is far faster than checking every item.
Why must the array be sorted for binary search?
Binary search decides which half to keep by comparing the target with the middle element. That decision is only correct if everything to the left is smaller and everything to the right is larger — which is exactly what a sorted array guarantees. On an unsorted array the result would be wrong.
What is the time complexity of binary search?
Binary search runs in O(log n) time because each step halves the number of elements left to check. For a million items it needs only about twenty comparisons, compared with up to a million for a linear search, which is why it is so much faster on large sorted data.
What is the difference between iterative and recursive binary search?
Both use the same halving logic. The iterative version uses a loop and updates low and high until they cross, using constant extra space. The recursive version calls itself on the chosen half; it is elegant but uses stack space for each call. The results are identical.
How does binary search find the middle element?
It computes the middle index as low + (high - low) / 2. Writing it this way instead of (low + high) / 2 avoids a possible overflow when low and high are very large, while still landing on the middle position.
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.