Tuesday, 17 December 2019

Binary Search in C

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
main()
{
int c=0,f=0,i,num,beg,*arr,n,end;
printf("\n Enter the number of elements ");
scanf("%d",&n);
arr=(int*)malloc(n*2);
for(i=0;i<n;i++)
{
  printf("\n Enter element %d :",i);
  scanf("%d",(arr+i));
}
printf("\n Enter the element to be searched ");
scanf("%d",&num);
beg=0,end=n-1;
while(beg<=end)
{
int mid=(beg+end)/2;
if(*(arr+mid)==num)
{
c++;
printf("\n %d is present in the array at the position = %d ",num,mid);
f=1;
break;
}
else if(*(arr+mid)>num)
end=mid-1;
else
beg=mid+1;
c++;
}
if(beg>end && f==0)
printf("\n %d does not exist in the array ",num);
getch();
}

No comments:

Post a Comment

Convey your thoughts to authors.