Program to search an element using binary search.
#include<stdio.h>
int main()
{
int i,a[10],n,b,c=0,l,f,mid;
printf("Enter the size limit maximum is 10\n");
scanf("%d",&n);
printf("Enter the array element\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched\n");
scanf("%d",&b);
f=0;
l=n-1;
while(f<=l)
{
mid=(f+l)/2;
if(b<a[mid])
{
l=mid-1;
}
if(b>a[mid])
{
f=mid+1;
}
else if(b==a[mid])
{
c=1;
break;
}
}
if(c==0)
{
printf("Element not found");
}
else
{
printf("Element found at %d position",mid+1);
}
}
OUTPUT
Enter the size limit maximum is 10
4
Enter array element
4
6
3
9
Enter the element to be searched
6
Element found at 2 position
Comments
Post a Comment