C program to binary search using recursion
Input:
5
1 2 3 4 5
3
Output:
3 is found
Implementation:
/*
Source: http://www.coderegister.co.in/2015/07/binary-search-to-search-element-in-array.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/* Binary search to search an element in the array */
int binarysearch(int *a,int l,int r,int e)
{
int mid;
if(l<r)
{
/* Calculate the middle index of the array */
mid=(l+r)/2;
/* If the middle element is the element we are searching, return the middle index */
if(*(a+mid)==e)
return 1;
/* Else recur for starting index to mid-1 */
else if(e<*(a+mid))
return binarysearch(a,l,mid-1,e);
/* Else recur for mid+1 index to end */
else
return binarysearch(a,mid+1,r,e);
}
return 0;
}
int main(void) {
int *a,n,i,element;
/* allocate the memory */
a=(int*)malloc(sizeof(int)*100);
/* get the number of elements of the array */
scanf("%d",&n);
/* get the elements of the array */
for(i=0;i<n;i++)
scanf("%d",(a+i));
/* Get the element to search in the array */
scanf("%d",&element);
/* If the function return value is true, then the element is in the array */
if(binarysearch(a,0,n,element))
printf("%d is found",element);
/* else the element is not found in the array */
else
printf("%d is not found",element);
return 0;
}