Advanced C++ Programming and Algorithms

# Implementing Binary Search in C++

## Introduction

The interval search algorithm family includes the binary search algorithm. Comparing this approach to the linear search algorithm, it is significantly more effective. Only sorted data structures can be used for binary search. The search space is divided in half and the centre of the sorted data structure is continually targeted by this method until the match is discovered. Binary search algorithm's temporal complexity is O (Log n).

## Working

- Divide the search interval in half periodically to search the sorted array.
- Start with an interval that encompasses the entire array.
- Narrow the interval to the bottom half if the search key's value is smaller than the item in the interval's midpoint.
- If not, then make it narrow to the top half.
- Continue checking until the interval is empty or the value is located.

## Algorithm to perform Binary Search

*Take input array, left, right & x**START LOOP – when left exceeds or is equal to right*

*mid = left + (right-left)/2**if(arr[mid]==x) then**return m**else if(arr[mid] less than x) then**left = m + 1**else**right= mid – 1*

*END LOOP**return -1*

## C++ Program to Implement Binary Search

**Algorithmic Complexity**

## Conclusion

I hope this tutorial helped you understand how binary search is implemented in C++. This method is frequently used to determine an element's location in an array or list that has been sorted. We spoke about the iterative and recursive approaches to binary search. With a few little changes to the code, both approaches use the same logic. If you want to study C++, you may read some of our other articles.