C program to implement Binary Search

//Binary Search

#include<stdio.h>

int main()
{
int beg,end,mid,item,n,data[20];

printf(“\nPlease Enter Number of elements in an array\n”);
scanf(“%d”, &n);

for(int i = 0; i <n; ++i)
{
scanf(“%d”, &data[i]);
}
printf(“Enter the item to search\n”);
scanf(“%d”,&item);

beg=0;
end=n;
mid=((beg+end)/2);
while((beg<=end)&&(data[mid]!=item))
{
if(data[mid]>item)
end=mid-1;
else
beg=mid+1;
mid=((beg+end)/2);
}

if(data[mid]==item)
printf(“\nBinary search successfully found searching item %d in location %d”,item,mid);
else
printf(“\nData is not in the array”);
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>