Wednesday, 29 October 2014

Binary Search

#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],b,i,j,mid,top,bottom,n;
printf("Enter how many elements you want:\n");
scanf("%d",&n);
printf("Enter the %d elements in ascending order\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the b to  search\n");
scanf("%d",&b);
bottom=1;
top=n;
do
{
mid=(bottom+top)/2;
if(b<a[mid])
{
top=mid-1;
}
else if(b>a[mid])
{
bottom=mid+1;
}
}while(b!=a[mid]&&bottom<=top);
if(b==a[mid])
{
printf("Binary search successfull!!\n");
printf("\n %d found in position: %d\n",b,mid+1);
}
else
{
printf("\n  Search failed\n %d not found\n",b);
}
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.