19)Write a C program for implementing binary search method using function.


#include<stdio.h>
#include<conio.h>
#define MAX 20
int bsearch(int [],int,int,int);
void main()
{
int a[10],i,t,f=0,n,l,k;
int bsearch(int[],int,int,int);
clrscr();
printf(“\n\nENTER THE SIZE OF AN ARRAY”);
scanf(“%d”,&n);
if (n>MAX)
{
printf(“\n\nINVALIED INDEX \n\n”);
}
else
{
printf(“\n\nENTER THE ARRAY ELEMENTS\n\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“\n\nENTER THE ELEMENT FOR SEARCH”);
scanf(“%d”,&t);
l=n-1;
k=bsearch(a,f,l,t);
if(k==-1)
{
printf(“\n\nELEMENT IS NOT FOUND\n”);
}
else
{
printf(“\n\nELEMENT IS FOUND AT LOCATION =%d”,k);
}
}
getch();
}
int bsearch(int list[],int f,int l,int t)
{
int m;
while(f<=l)
{
m=(f+l)/2;
if(list[m]==t)
return m;
else if(t<list[m])
l=m-1;
else if(t>list[m])
f=m+1;
}
return(-1);

}

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