Open In App

C++ Program For Binary Search

Last Updated : 07 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about the Binary Search algorithm and how to implement it in a C++ program.

Binary Search is a search algorithm that is faster than the linear search algorithm. Binary Search is used to search the position of the target element in a sorted array by repeatedly dividing the search space in half. Binary search eliminates half portion of the array with each comparison. It works in a time complexity of O(log n) where n is the number of elements in the array.

How does Binary Search works?

The idea is to compare the middle element with the target value, if the middle element is equal to the target value, the index of the middle element is the position of the target value.

If the target value is smaller than the middle element, the target value is searched in the left half of the current space and If the target value is greater than the middle element, the target value is searched in the right half of the current space. This is done until the target element is found if the element is present in the array.

Examples

Input: arr[] = {10, 20, 30, 50, 60, 80, 110, 130, 140, 170}, x = 110
Output: 6
Explanation: Element x is present at index 6. 

Input: arr[] = {10, 20, 30, 40, 60, 110, 120, 130, 170}, x = 175
Output: -1
Explanation: Element x is not present in arr[].

Illustration of Binary Search Algorithm

binary search in c++

Example of Binary Search Algorithm

The middle index of the array can be calculated as:

int mid = low + (high – low)/2;

Binary Search Program in C++ (Recursive)

C++




// C++ program to implement recursive Binary Search
  
#include <bits/stdc++.h>
using namespace std;
  
// Recursive Binary Search function to find the index of an
// element 'x' in a sorted array 'arr' if elements is
// present, otherwise it return -1
  
// low: The index of the first element in the current
// sub-array high: The index of the last element in the
// current sub-array
int binarySearch(int arr[], int low, int high, int x)
{
    // Base case: If the search space becomes empty, the
    // element is not present in the array
    if (high >= low) {
        // Calculate the middle index to divide the search
        // space in half
        int mid = low + (high - low) / 2;
  
        // If the middle element is equal to 'x', we have
        // found the element, return its index
        if (arr[mid] == x)
            return mid;
  
        // If the middle element is greater than 'x', search
        // in the left half of the array
        if (arr[mid] > x)
            return binarySearch(arr, low, mid - 1, x);
  
        // If the middle element is less than 'x', search in
        // the right half of the array
        return binarySearch(arr, mid + 1, high, x);
    }
  
    // If the base case is reached, the element is not
    // present in the array, return -1
    return -1;
}
  
// Driver code
int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
  
    // Element to be searched
    int x = 10;
    int n = sizeof(arr) / sizeof(arr[0]);
    int result = binarySearch(arr, 0, n - 1, x);
    (result == -1)
        ? cout << "Element is not present in array"
        : cout << "Element is present at index " << result;
  
    return 0;
}


Output

Element is present at index 3

Complexity Analysis

  • Time Complexity : O(log n)
  • Auxiliary Space : O(log n)

Binary Search Program in C++ (Iterative)

C++




// C++ program to implement
// iterative Binary Search
#include <bits/stdc++.h>
using namespace std;
  
// Iretative Binary Search function to find the index of an
// element 'x' in a sorted array 'arr' if elements is
// present, otherwise it return -1
  
// low: The index of the first element in the current
// sub-array high: The index of the last element in the
// current sub-array
int binarySearch(int arr[], int low, int high, int x)
{
    while (low <= high) {
        int mid = low + (high - low) / 2;
  
        // If the middle element is equal to 'x', we have
        // found the element, return its index
        if (arr[mid] == x)
            return mid;
  
        // If the middle element is smaller than 'x', search
        // in the right half of the array
        if (arr[mid] < x)
            low = mid + 1;
  
        // If the middle element is greater than 'x', search
        // in the left half of the array
        else
            high = mid - 1;
    }
  
    // If the base case is reached, the element is not
    // present in the array, return -1
    return -1;
}
  
// Driver code
int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
  
    // Element to be searched
    int x = 10;
    int n = sizeof(arr) / sizeof(arr[0]);
    int result = binarySearch(arr, 0, n - 1, x);
    (result == -1)
        ? cout << "Element is not present in array"
        : cout << "Element is present at index " << result;
    return 0;
}


Output

Element is present at index 3

Complexity Analysis

  • Time Complexity : O(log n)
  • Auxiliary Space : O(1)

Please refer complete article on Binary Search for a better understanding.

Related Articles



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads