15)Write a C program to search given element into the list using binary search method.


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

getch();
}

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