C Program to Implement Binary Search
Get Certified in C Programming and Take Your Skills to the Next Level
Program 1
// Binary Search in C
#include<stdio.h>
#include<conio.h>
int main()
{
int ar[500],n,i,j,temp,beg,end,mid,f=0,s;
xyz:printf("\nEnter limit for array");
scanf("%d",&n);
if(n>500)
{
printf("\nInvalid limit pls enter between 1 to 500");
goto xyz;
}
printf("\nEnter elements in array");
for (i = 0; i <n ; i++)
scanf("%d",&ar[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(ar[j]<ar[i])
{
temp=ar[i];
ar[i]=ar[j];
ar[j]=temp;
}
}
}
printf("\nEnter an element for search");
scanf("%d",&s);
beg=0;
end=n-1;
while(beg<=end)
{
mid=(beg+end)/2;
if(s==ar[mid])
{
f=1;
break;
}
else
if(s>ar[mid])
beg=mid+1;
else
end=mid-1;
}
if(f==1)
printf("\nSearching success");
else
printf("\nSearching not success");
return 0;
}
Your opinion matters
Please write your valuable feedback about DataFlair on Google

