Binary Search in C Program Using Recursion

Binary search in c program using recursion for beginners to learn some important concepts of c programming language to implement and execute binary search algorithm in c using recursion method

Binary Search in C Program Using Recursion

Binary search is a fast way to find a specific item in a sorted list of things. It works by dividing the section of the list that could contain the item in half until you’ve reduced down the options to just one. 

Binary search is a fast way to find a specific element in a sorted array, analogous to looking up a word in the dictionary. When searching for a word that begins with the letter S, one normally begins searching the dictionary about halfway through.

Recursion Method in C

In C programming, it is permissible for a function to call itself. A recursive function is one that repeatedly invokes itself, either directly or indirectly, until a stated condition is met. A process in which a function calls itself a subroutine is known as recursion. Because the function calls itself during execution, it can be repeated multiple times. Recursive functions are functions that incorporate recursion.

#include <stdio.h>
int binary(int [], int, int, int);
int main()
{
int c, initial, end, n, search, array[100], index;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
initial = 0;
end = n - 1;
index = binary(array, initial, end, search);
if (index == -1)
printf("Not found! %d\n", search);
else
printf("%d is present at location %d\n", search, index + 1);
}

int binary(int a[], int s, int e, int f) 
{
int m;
if (s > e) 
return -1;
m = (s + e)/2;
if (a[m] == f) 
return m;
else if (f > a[m]) 
return binary(a, m+1, e, f);
else
return binary(a, s, m-1, f);
}

Output:

Enter number of elements
5
Enter 5 integers
34
56
67
87
78
Enter value to find
67
67 is present at location 3