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

Binary Search: Recursive approach

Binary Search: Recursive approach

What you'll learn: How to split a sorted array in half repeatedly using a function that calls itself to find a target value.

Divide and Conquer

In the iterative version of binary search, we used a while loop to narrow down our search range. In the recursive approach, we treat the problem as a series of identical sub-problems.

Imagine you are looking for a word in a physical dictionary. You open it to the middle. If the word isn't there, you are left with a smaller dictionary (either the left half or the right half). You then perform the exact same "open to the middle" action on that smaller section. Recursion is simply the act of a function calling itself to solve these smaller versions of the same task.

The Logic of the Recursive Call

To make this work in C, our function needs to know the current boundaries (low and high) for every call.

  1. The Base Case: If low becomes greater than high, we’ve run out of elements. The search fails.
  2. The Middle: We find the midpoint. If it’s our target, we’re done!
  3. The Recursive Step: If the target is smaller than the middle, we call the function again, but we update the high boundary. If it’s larger, we call it again and update the low boundary.

Implementation in C

Here is how you translate that logic into code:

#include <stdio.h>

int recursiveBinarySearch(int arr[], int low, int high, int target) {
    // Base case: the search range is empty
    if (low > high) {
        return -1;
    }

    int mid = low + (high - low) / 2;

    // Found the target
    if (arr[mid] == target) {
        return mid;
    }

    // Target is in the left half
    if (target < arr[mid]) {
        return recursiveBinarySearch(arr, low, mid - 1, target);
    }

    // Target is in the right half
    return recursiveBinarySearch(arr, mid + 1, high, target);
}

int main() {
    int data[] = {2, 5, 8, 12, 16, 23, 38};
    int n = 7;
    int result = recursiveBinarySearch(data, 0, n - 1, 16);
    
    if (result != -1)
        printf("Element found at index: %d", result);
    else
        printf("Element not found");
        
    return 0;
}

Why use recursion?

While recursion uses more memory (due to the "stack" of function calls), the code is often considered cleaner and more elegant. It maps directly to the mathematical definition of binary search: "To search a list, search the middle, then search the remaining half."

Key takeaway

Recursive binary search solves the problem by passing a smaller "window" of the array into a new call of the same function until the target is found or the window closes.