Binary search is very fast as compared to linear search. it divides the given array into two halves each time a loop executes and then compares the value.
//use header files syntax according to the compiler
#include<iostream.h>
#include<conio.h>
#include<conio.h>
//enter values in the array in ascending order only
void main()
{
int arr[20],beg,mid,end,i,n,num;
flag=0;
cout << "\n Enter the size of an array ";
cin >> n;
cout << "\n Enter the values \n";
for(i = 0; i < n;i++)
{
cin >> arr[i];
}
beg = 0;
end = n-1;
cout << "\n Enter a value to be searched in an array ";
cin >> num;
while( beg <= end)
{
mid = (beg+end)/2;
if(arr[mid] == num)
{
flag=1;
break;
}
else if(num > arr[mid])
{
beg=mid+1;
}
else if (num < arr[mid])
{
end=mid-1;
}
}
if (flag==0)
cout << "Number does not found.";
else
cout<<"no found at "<<mid+1<<"position";
getch();
}
}