C PROGRAMMING PROGRAM • FUNCTIONS & RECURSION

Perform Binary Search Using Recursion

Learn how to perform binary search using recursion using a clear C program.

AdvancedRecursionBinary searchSorted array

PROBLEM UNDERSTANDING

Input and expected output

Sample input
7
2 5 8 12 16 23 38
23
Sample output
Found at position 6

COMPLETE C PROGRAM

Complete C implementation

binary-search-recursion.c
Open in compiler
#include <stdio.h>

int binarySearch(const int values[], int left, int right, int target)
{
    if (left > right) return -1;
    int middle = left + (right - left) / 2;
    if (values[middle] == target) return middle;
    if (values[middle] < target) return binarySearch(values, middle + 1, right, target);
    return binarySearch(values, left, middle - 1, target);
}

int main(void)
{
    int size, values[100], target;

    scanf("%d", &size);
    if (size < 1 || size > 100) return 1;
    for (int index = 0; index < size; index++) scanf("%d", &values[index]);
    scanf("%d", &target);
    int position = binarySearch(values, 0, size - 1, target);
    if (position >= 0) printf("Found at position %d\n", position + 1);
    else printf("Not found\n");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Found at position 6
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Return a result from the half selected by comparing the target with the middle element.
  3. Display the computed result.

Return a result from the half selected by comparing the target with the middle element.

EFFICIENCY

Time and space complexity

Time complexity

O(log n)

Auxiliary space

O(log n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.