![]() |
VOOZH | about |
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++.
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.
8 found.
Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: Implementation defined, discussed below.
To implement binary search manually, we first need to understand how binary search 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:
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.
Here we use loop to continue the process of comparing the target element and splitting the search space in two halves.
8 found.
Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: O(1)
We can also implement the binary search algorithm with recursion instead of loops.
8 NOT found.
Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: O(log n)