C Program For Binary Search
#include<stdio.h>
int main()
{
int a[100],i,n,item,flag=0,low,high,mid,j,temp;
printf("How many numbers\n");
scanf("%d",&n);
printf("Enter the value in array:-\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for (j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Enter item to be searched:\n");
scanf("%d",&item);
low=0;
high=n-1;
do
{
mid=(low+high)/2;
if(item>a[mid])
{
low=mid+1;
flag=0;
}
else if (item<a[mid])
{
high=mid-1;
flag=0;
}
else
{
flag=1;
break;
}
}
while(item!=a[mid]&&low<=high);
if(flag==1)
printf("\nItem found");
else
printf("\nItem not found");
return 0;
}
OUTPUT
Post A Comment:
0 comments so far,add yours