#include
void main()
{
int a[100],n,i,key,p;
int binary_search(int [],int,int);
clrscr();
printf("\nHow many integers=>");
scanf("%d",&n);
printf("\nEnter integers(sorted)=>");
for(i=0;i
printf("\nEnter the element to be searched=");
scanf("%d",&key);
if((p=binary_search(a,n,key)) == -1)
printf("\n%d is not present\n",key);
else
printf("\n%d is present at position %d\n",key,p+1);
getch();
}
int binary_search(int x[],int n,int key)
{
int l,h,m;
l=0;
h=n-1;
while(l<=h)
{
m=(l+h)/2;
if(key < x[m])
h=m-1;
else if(key > x[m])
l=m+1;
else return(m);
}
return(-1);
}
No comments:
Post a Comment