C Program to search a key element using binary search using recursion
Program
#include<stdio.h>
int binary_search(int a[], int low, int high, int key)
{
int mid;
if(low > high)
return 0;
mid = (low + high)/2;
if(key == a[mid])
{
return mid + 1;
}
if(key < a[mid])
binary_search(a, low, mid - 1, key);
else
binary_search(a, mid + 1, high, key);
}
void main()
{
int n, i, present_flag, a[10], key;
printf("Enter the size of the array\n");
scanf("%d", &n);
printf("Enter %d elements in ascending order\n", n);
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key element to be searched\n");
scanf("%d", &key);
present_flag = binary_search(a, 0, n - 1, key);
if(present_flag == 0)
printf("Element not found\n");
else
printf("Element found at position %d\n", present_flag);
}
Output 1
Enter the size of the array
7
Enter 7 elements in ascending order
9
11
21
27
36
44
60
Enter the key element to be searched
60
Element found at position 7
Output 2
Enter the size of the array
5
Enter 5 elements in ascending order
1
12
30
41
44
Enter the key element to be searched
1
Element found at position 1
Output 3
Enter the size of the array
5
Enter 5 elements in ascending order
22
30
37
50
51
Enter the key element to be searched
70
Element not found