Binary search program using c
Binary search program
#include<stdio.h>#include<conio.h>
void main()
{
int a[30],i,n,low,high,mid,term,flag=0;
clrscr();
printf("Enter the number of elements in array");
scanf("%d",&n);
printf("Enter elements in ascending order:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the elements to search:\n");
scanf("%d",&term);
low=0;
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])
{
flag=1;
break;
}
}
if(flag==1)
printf("\n search is successful\n");
else
printf(" search is not successful"):
getch();
}
Output
Enter the number of elements:3Enter the elements in ascending order:
10
15
20
Enter the elements to be searched:20
The element is found
No comments: