Course contentsShow
← C
Lesson 1062 of 1,21914. Data Structures in CFree lesson

Binary Search: Iterative approach

Binary Search: Iterative approach

What you'll learn: How to efficiently find a value in a sorted array by repeatedly cutting the search area in half using a while loop.

The "Dictionary" Strategy

Imagine you are looking for the word "Panda" in a physical dictionary. You wouldn't start at page one and flip through every single sheet (that is Linear Search). Instead, you open the book to the middle. If you see words starting with "M," you know "Panda" must be in the right half. You ignore the left half entirely and repeat the process.

This is Binary Search. In C, we implement this iteratively using a loop and three markers: low, high, and mid.

Crucial Requirement: The array must be sorted before you start.

How the Code Works

We use a while loop that continues as long as our low marker hasn't passed our high marker. Inside, we calculate the mid point. If the middle element is our target, we are done! If the target is smaller, we move our high marker to the left of the middle. If it’s larger, we move our low marker to the right.

#include <stdio.h>

int binarySearch(int arr[], int size, int target) {
    int low = 0;
    int high = size - 1;

    while (low <= high) {
        // Calculate the middle index
        int mid = low + (high - low) / 2;

        // Check if target is at mid
        if (arr[mid] == target) {
            return mid; // Found it!
        }

        // If target is greater, ignore left half
        if (arr[mid] < target) {
            low = mid + 1;
        } 
        // If target is smaller, ignore right half
        else {
            high = mid - 1;
        }
    }

    return -1; // Target not found
}

int main() {
    int myData[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
    int n = 10;
    int target = 23;
    
    int result = binarySearch(myData, n, target);
    
    if (result != -1)
        printf("Element found at index: %d", result);
    else
        printf("Element not present in array");
        
    return 0;
}

Why Use It?

Linear search takes O(n)O(n) time—if you have a million items, you might check a million items. Binary Search takes O(log⁡n)O(\log n) time. For a sorted list of one million items, Binary Search will find your target (or prove it isn't there) in just about 20 steps. By discarding half the data with every loop iteration, the search space shrinks incredibly fast.

Key takeaway

Binary Search is a "divide and conquer" algorithm that finds elements in sorted arrays by repeatedly halving the search range, making it significantly faster than checking every element.