BINARY SEARCH IN C-RECURSIVE AND NON-RECURSIVE PROCEDURE

#include<stdio.h>
#define N 5
int nbinsearch(int a[],int);
int rbinsearch(int a[],int, int,int);
main()
{
int a[10];
int i,j,s,temp,ch,l,h;
printf(“enter the elements\n”);
for(i=0;i<N;i++)
scanf(“%d”,&a[i]);
printf(“the sorted array is:\n”);
for(i=0;i<N;i++)
{
for(j=i+1;j<=N;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(i=0;i<N;i++)
printf(“%d\t”,a[i]);

do
{
printf(“\nmenu\n1.nbinsearch\n2.rbinsearch\n3.exit\n”);
printf(“enter the choice\n”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:printf(“enter the element to be searched\n”);
scanf(“%d”,&s);
nbinsearch(a,s);
break;
case 2:printf(“enter the element to be searched\n”);
scanf(“%d”,&s);
l=0;
h=N-1;
rbinsearch(a,l,h,s);
break;
case 3:break;
}
}while(ch!=3);
}
int nbinsearch(int b[N],int s)
{
int i,j,mid,low=0,high=N-1;

while(low<=high)
{
mid=(low+high)/2;
if(s==b[mid])
{
printf(“search successful\n”);
return(-1);
}
else

if(s<b[mid])
high=(mid-1);
else
if(s>b[mid])
low=mid+1;

}
printf(“not found\n”);
return -1;
}
int rbinsearch(int b[N],int low,int high,int s)
{
int mid;
if(low>high)
printf(“element not found\n”);
else
{
mid=(low+high)/2;
if(s==b[mid])
printf(“search successful\n”);
if(s>b[mid])
rbinsearch(b,mid+1,high,s);
if(s<b[mid])
rbinsearch(b,low,mid-1,s);
}
}

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