The Wayback Machine - https://web.archive.org/web/20240825173849/https://www.geeksforgeeks.org/cpp-binary-search/
Open In App

C++ Program For Binary Search

Last Updated : 07 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
44.32%
5.1L

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



Previous Article
Next Article

Similar Reads

Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include &lt;bits/stdc++.h&gt; using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
What is the difference between Binary Search and Jump Search?
Binary Search and Jump Search are two popular algorithms used for searching elements in a sorted array. Although they both try to identify a target value as quickly as possible, they use distinct approaches to get there. In this article, we will discuss the difference between binary search and jump search. Let's explore how these algorithms optimiz
2 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Count the Number of Binary Search Trees present in a Binary Tree
Given a binary tree, the task is to count the number of Binary Search Trees present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes. Input: 11 / \ 8 10 / / \ 5 9 8 / \ 4 6 Output: 6 Sub-tree rooted under node 5 is a BST 5 / \ 4 6 Another BST we have is rooted
10 min read
Total number of possible Binary Search Trees and Binary Trees with n keys
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan number Cn = (2n)! / ((n + 1)! * n!) For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees. Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n
12 min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children.  Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, w
2 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read
C Program for Binary Search Tree
A binary Search Tree is a binary tree where the value of any node is greater than the left subtree and less than the right subtree. In this article, we will discuss Binary Search Trees and various operations on Binary Search trees using C programming language. Properties of Binary Search Tree Following are some main properties of the binary search
7 min read
Breadth-first Search is a special case of Uniform-cost search
In AI there are mainly two types of search techniques: Un-informed/blind search techniquesInformed search techniques Search algorithms under the Uninformed category are: Breadth-first searchUniform cost searchDepth-first searchDepth limited searchIterative deepening depth-first searchBidirectional search Search algorithms under the Informed categor
6 min read
Anagram Substring Search (Or Search for all permutations) | Set 2
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Examples: Input: txt[] = "BACDGABCDA" pat[] = "ABCD"Output: Found at Index 0 Found at Index 5 Found at Index 6 Input: txt[] = "AAABABAA" p
10 min read
Difference between Best-First Search and A* Search?
Best-First Search: Best-First search is a searching algorithm used to find the shortest path which uses distance as a heuristic. The distance between the starting node and the goal node is taken as heuristics. It defines the evaluation function for each node n in the graph as f(n) = h(n) where h(n) is heuristics function. A*Search: A*search is a se
2 min read
Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
15 min read
Search a Word in a 2D Grid of characters (Word Search)
Given a 2D grid of characters and a single word/an array of words, find all occurrences of the given word/words in the grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match in this direction (not in zig-zag form).The 8 directions are, Horizontally Left, Horizontally Right, Vert
15+ min read
Sublist Search (Search a linked list in another list)
Given two linked lists, the task is to check whether the first list is present in 2nd list or not. Examples: Input: list1 = 10-&gt;20 list2 = 5-&gt;10-&gt;20 Output : LIST FOUNDInput: list1 = 1-&gt;2-&gt;3-&gt;4 list2 = 1-&gt;2-&gt;1-&gt;2-&gt;3-&gt;4 Output: LIST FOUNDInput: list1 = 1-&gt;2-&gt;3-&gt;4 list2 = 1-&gt;2-&gt;2-&gt;1-&gt;2-&gt;3 Outpu
15+ min read
Best First Search (Informed Search)
In BFS and DFS, when we are at a node, we can consider any of the adjacent as the next node. So both BFS and DFS blindly explore paths without considering any cost function.  The idea of Best First Search is to use an evaluation function to decide which adjacent is most promising and then explore. Best First Search falls under the category of Heuri
9 min read
Repeatedly search an element by doubling it after every successful search
Given an array "a[]" and integer "b". Find whether b is present in a[] or not. If present, then double the value of b and search again. We repeat these steps until b is not found. Finally we return value of b. Examples: Input : a[] = {1, 2, 3} b = 1 Output :4 Initially we start with b = 1. Since it is present in array, it becomes 2. Now 2 is also p
6 min read
Difference Between Linear Search and Jump Search
Linear Search and Jump Search are two different techniques used to find an element in a list. Each algorithm has its own set of characteristics, advantages, and limitations, making them suitable for different scenarios. This article explores the key differences between Linear Search and Jump Search. What is Linear Search?Linear Search, also known a
3 min read
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read