Saturday, May 21, 2011

C program to implement Binary Search

#include
#include
int main()
{
int a[50],item,n,beg,last,mid,i;
printf("\n\n\t\t enter desired array size ");
scanf(" %d",&n);
printf("\n\n\t\t enter array elements \n");
for(i=0;i< n ;i++)
{
scanf("%d",&a[i]);
}
printf("\n\n\t\t enter elements to be searched for");
scanf("%d",&item);
beg=0;
last=n-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(item==a[mid])
{
printf("\n\n\t\t element found at position %d",mid+1);
}
else if(item>a[mid])
beg=mid+1;
else
last=mid-1;
printf("\n\n\t\t element not found");
}
getch();
}

No comments:

Post a Comment