Here you will learn about binary search in C++.

Binary search is an algorithm used to search for an element in a sorted array. In this algorithm the targeted element is compared with middle element. If both elements are equal then position of middle element is returned and hence targeted element is found.

If both elements are unequal then if targeted element is less or more than middle element we discard the lower or upper half and the search continues by finding new middle element.

**Also Read: Linear Search in C++**

Below program shows how to implement binary search algorithm in C++.

## Program for Binary Search in C++

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
#include<iostream> using namespace std; int main() { int search(int [],int,int); int n,i,a[100],e,res; cout<<"How Many Elements:"; cin>>n; cout<<"\nEnter Elements of Array in Ascending order\n"; for(i=0;i<n;++i) { cin>>a[i]; } cout<<"\nEnter element to search:"; cin>>e; res=search(a,n,e); if(res!=-1) cout<<"\nElement found at position "<<res+1; else cout<<"\nElement is not found....!!!"; return 0; } int search(int a[],int n,int e) { int f,l,m; f=0; l=n-1; while(f<=l) { m=(f+l)/2; if(e==a[m]) return(m); else if(e>a[m]) f=m+1; else l=m-1; } return -1; } |

**Output**

*How Many Elements:5*

*Enter Elements of Array in Ascending order*

* 12 39 40 68 77*

*Enter element to search:40*

*Element found at position 3*

Comment below if you have any doubts related to above program for binary search in C++.

Best blog ever

The above code has a problem.

If the required element is at position 0, it gives output as element not found.!!!!

please correct me if i am wrong!

There was a little mistake in code, now I have fixed. Thanks Satish for telling ðŸ™‚

What if there are 2 same numbers at different positions in the array and we want to find both of their’s position using BS???

wHy do we use the for loop here

In Binary search its is possible to use of do….while loop and switch case statment..?

what does the “m=(f+1)/2 ” does in “a” vector index seem to me very confusing since when “m” get a no integer number it won’t be able to show the position