Binary Search in C using Recursion


#include<stdio.h>

void bins(int lb,int ub,int item,int a[]);
void main()
{
int i,n,item,a[20];
printf("Enter the size of an array: ");
scanf("%d",&n);

printf("Enter the elements of the array: " );
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

printf("Enter the number to be search: ");
scanf("%d",&item);


bins(0,n-1,item,a);

}

void bins(int lb,int ub,int item,int a[])
{
int mid,flag=0;

if(lb<=ub)
{
mid=(lb+ub)/2;
if(item==a[mid])
{
flag=flag+1;
}
else if(item<a[mid])
{
return bins(lb,mid-1,item,a);
}
else
return bins(mid+1,ub,item,a);
}


if(flag==0)
printf("Number is not found.");
else
printf("Number is found at %d", mid+1);
}


Comments

Popular posts from this blog

Write a Program to Add two 3x3 Matrix using C

C program for Unit Conversion

Write a Program to Add two 5x5 Matrix using C