Binary Search in C++

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++

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++.

6 thoughts on “Binary Search in C++

  1. satish

    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!

    Reply
    1. Admin Post author

      There was a little mistake in code, now I have fixed. Thanks Satish for telling 🙂

      Reply
  2. Harris

    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???

    Reply
  3. bhargav

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

    Reply

Leave a Reply

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