Binary Search in C++
Binary search in c++ uses for statement
and if-else statement. Binary search is performed on sorted array. You can
enter sorted array values directly and you can also sort through bubble sort or
any other sorting technique. Binary search is better searching technique as
compared to linear search because binary search takes less time for searching.
In binary search, we use three
variables start, last and mid to represent starting, ending and middle value of
an array. In while loop, every time we compare variable mid to searching item.
If array middle value is less than searching item, then variable start is
assigned to variable mid+1. Else if variable mid is equal to searching item,
then is printed on screen. Else, variable last is assigned to mid-1. After that
mid is assigned to (start+last)/2. It is continued to while till
start<=last.
C++ Program for Binary Search
#include<iostream>
using namespace std;
int main()
{
int
arr[10],s,i,l,start,last,mid;
cout<<"Enter
the length of an array : ";
cin>>l;
cout<<endl<<"Enter array elements in sorted values
(asc/dsc)"<<endl;
for(i=0;i<l;i++)
{
cout<<endl<<"Enter the value of element no
"<<i+1<<" : ";
cin>>arr[i];
}
cout<<endl<<"Enter the value to be search : ";
cin>>s;
start=0;
last=l-1;
mid=(start+last)/2;
while(start<=last)
{
if(arr[mid]<s)
{
start=mid+1;
}
else
if(arr[mid]==s)
{
cout<<endl<<s<<" is present in array at location
"<<mid+1;
break;
}
else
last=mid-1;
mid=(start+last)/2;
}
if(start>last)
{
cout<<endl<<s<<" is not present in array";
}
return 0;
}
OUTPUT 1:
Enter the length of an array : 5
Enter array elements in sorted values
(asc/dsc)
Enter the value of element no 1 : 2
Enter the value of element no 2 : 8
Enter the value of element no 3 : 9
Enter the value of element no 4 : 4
Enter the value of element no 5 : 6
Enter the value to be search : 9
9 is present in array at location 3
OUTPUT 2:
Enter the length of an array : 5
Enter array elements in sorted values
(asc/dsc)
Enter the value of element no 1 : 4
Enter the value of element no 2 : 8
Enter the value of element no 3 : 6
Enter the value of element no 4 : 2
Enter the value of element no 5 : 3
Enter the value to be search : 1
1 is not present in array