Nothing Special   »   [go: up one dir, main page]

Open In App

C++ Program For Binary Search

Last Updated : 14 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

C++
// C++ program to illustrate how to use the
// std::binary_search() function
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 8, 9, 11};

    // Element to be searched
    int target = 8;
  
    // Check for the target in the vector v
    if (binary_search(v.begin(), v.end(), target)) {
      
        // If the value is found
        cout << target << " found.";
    } else {
      
        // If the value is not found
        cout << target << " NOT found.";
    }
    return 0;
}

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.

C++
// C++ program to implement iterative 
// binary search
#include <bits/stdc++.h>
using namespace std;

bool binarySearch(vector<int>& v, int target) {
    
      // Defining the part of the vector to be
      // searched
    int low = 0, high = v.size() - 1;
      
      // Till the element is found or vector cannot
      // be divided into more parts
    while (low <= high) {
      
          // Finding mid point
        int mid = ((high - low) / 2) + low;

        // If the middle element is equal to target
        if (v[mid] == target) {
            return true;
        }

        // If the middle element is greater than 
        // target, search in the left half 
        if (v[mid] > target)
            high = mid - 1;
        
        // If the middle element is smaller than
        // target, search the right half 
        else
            low = mid + 1;
    }
      
      // If we don't find the target
      return false;
}

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 8, 9, 11};
    
      // Element to be searched
      int target = 8;
  
      // Searching the target element
    if (binarySearch(v, target)) {
        cout << target << " found.";
    } else {
        cout << target << " NOT found.";
    }
    return 0;
}

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.

C++
// C++ program to implement recursive binary
// search
#include <bits/stdc++.h>
using namespace std;

bool binarySearch(vector<int>& v, int low,
                  int high, int target) {
    
      // If the range is invalid
    if (low > high) {
        return false;
    }

    // Finding mid point
    int mid = ((high - low) / 2) + low;

    // If the middle element is equal to target
    if (v[mid] == target) {
        return true;
    }

    // If the middle element is greater than
      // target,  search in the left half
    if (v[mid] > target) {
        return binarySearch(v, low, mid - 1,
                            target);
    }

    // If the middle element is smaller than
      // target, search in the right half
    return binarySearch(v, mid + 1, high,
                        target);
}

int main() {
    vector<int> v = {1, 5, 3, 2, 4, 9, 8, 11};

    // Element to be searched
    int target = 8;

    // Searching the target element using the
      // recursive function
    if (binarySearch(v, 0, v.size() - 1,target)) {
        cout << target << " found.";
    } else {
        cout << target << " NOT found.";
    }
    return 0;
}

Output
8 NOT found.

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



Next Article

Similar Reads

three90RightbarBannerImg