Write a C program for binary Search.


#include<stdio.h>
main()
{
int n,i,a[30],low=0,high,mid,term,flag=1;
printf("\n\n\t\tBINARY SEARCH\n");
printf("\t\t**************\n");
printf("\nEnter the Number of Elements :\n\n");
scanf("%d",&n);
printf("\n Enter the Elements in Ascending Order:\n\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Enter The Elements To Be Searched:\n\n");
scanf("%d",&term);
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(term<a[mid])
high=mid-1;
else
if(term>a[mid])
low=mid+1;
else
if(term==a[mid])
{
printf("\n SEARCH IS SUCCESSFUL\n");
printf("\n%d is Found at location %d",term,mid+1);
flag=0;
break;
}
}
if(flag)
printf("\n SEARCH IS UNSUCESSFUL");
getch();
}

0 comments:

Feel free to contact the admin for any suggestions and help.