Posted by: Sourav | July 29, 2015

Binary Search using recursion in C


#include<stdio.h>
int binsearch(int[],int,int,int);
void main()
{
int i,j,low,mid,up,found;
int arr[100];
for (i=0;i<10;i++)
{
//printf(“enter a number \n”);
//scanf(“%d”,&arr[i]);
arr[i]=i;
}

for (i=0;i<10;i++)
{
printf(“the number stored in %d place in the array is %d\n”,i,arr[i]);
//scanf(“%d”,&arr[i]);
}
printf(“enter a number \n”);
scanf(“%d”,&j);
low=arr[0];
up=arr[9];

found=binsearch(arr,arr[0],arr[9],j);
if (found==0)
printf(“element is found”);
else
printf(“element is  not found”);
}
int binsearch(int arr[100],int low,int up,int search)
{

int mid=(low+up)/2;
printf(“mid is %d\n”,mid);
if(search==mid)
return 0;
else if ((low==(up-1))||(up==low))
{
if(up==search)
return 0;
else
return 1;
}
else if (search>mid)
{
low=mid;
binsearch( arr,low,up,search);
}
else if (search <mid)
{
up=mid;
binsearch(arr,low,up,search);
}
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: