VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-binary-search/

⇱ C++ Program For Binary Search - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ Program For Binary Search

Last Updated : 23 Jul, 2025

Binary Search is a popular searching algorithm which is used for finding the position of any given element in a sorted array. It is a type of interval searching algorithm that keep dividing the number of elements to be search into half by considering only the part of the array where there is the probability of finding the target element.

In this article, we will learn how to implement binary search algorithm in C++.

Binary Search Using Library Function

C++ STL provides a built-in function std::binary_search() that implements the binary search algorithm for easy and quick search on sorted data. It returns true if the element is found, false otherwise. Its behaviour is undefined if the dataset is unsorted.


Output
8 found.

Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: Implementation defined, discussed below.

Manually Implement Binary Search in C++

To implement binary search manually, we first need to understand how binary search works.

How Binary Seach Works?

The binary search works by dividing the elements to be search into half in each pass. It is done by comparing the middle element with the target value. If the middle element is equal to the target value, then great, we have found the index of our target element. But if it's not, then we have two cases:

  • If the target value is smaller than the middle element, left half is considered as search space in next iteration.
  • If the target value is greater than the middle element, right half is considered as search space in next iteration.

This is done until the target element is found, or the dataset cannot be divided further inferring that element is not present.

As we can see, random access is needed to go to the mid-point and sorting is necessary to select the part of the dataset where the item might be present. It is for these reasons that binary search can only be applied to sorted arrays.

Binary Seach is easy to implement using both iteration and recursion.

Iterative Implementation

Here we use loop to continue the process of comparing the target element and splitting the search space in two halves.


Output
8 found.

Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: O(1)

Recursive Implementation

We can also implement the binary search algorithm with recursion instead of loops.


Output
8 NOT found.

Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: O(log n)

Comment