C PROGRAMMING PROGRAM • FUNCTIONS & RECURSION
Perform Binary Search Using Recursion
Learn how to perform binary search using recursion using a clear C program.
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
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Found at position 6
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Return a result from the half selected by comparing the target with the middle element.
- 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.
