A binary search is an algorithm for locating the position of an element in a sorted list by checking the middle, eliminating half of the list from consideration, and then performing the search on the remaining half. If the middle element is equal to the sought value, then the position has been found; otherwise, the upper half or lower half is chosen for search based on whether the element is greater than or less than the middle element. The method reduces the number of elements needed to be checked by a factor of two each time, and finds the target value, if it exists in logarithmic time.
Programming Language : C
[sourcecode language='c']
//To conduct Binary Search on an array of 10 elements stored in asscending order
#include
#include
void main()
{
int i,a[3],x,found,lb,ub,size,mid;
found=0; size=10; lb=0, ub=size-1;
for(i=0;i<3;i++)
{
printf("\nEnter the %d element : ",i+1);
scanf("%d",&a[i]);
}
printf("\n Enter the number you want to search : ");
scanf("%d",&x);
while(lb<=ub)
{
mid=(lb+ub)/2;
if(x==a[mid])
{
found=1;
break;
}
else if(x>a[mid])
lb=mid+1;
else
ub=mid-1;
}
if(found==1)
printf(“\n Success Number found! “);
else
printf(“\n Unsuccessful , Number not found!”);
}
[/sourcecode]






