X

Binary Search Algorithm – Iterative and Recursive Implementation

Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N).

Binary search is a search algorithm used to find the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half until the target value is found or the interval is empty. The search interval is halved by comparing the target element with the middle value of the search space.

Conditions to apply Binary Search Algorithm in a Data Structure

To apply Binary Search algorithm:

  • The data structure must be sorted.
  • Access to any element of the data structure should take constant time.

Binary Search Algorithm

Below is the step-by-step algorithm for Binary Search:

  • Divide the search space into two halves by finding the middle index “mid”.
  • Compare the middle element of the search space with the key.
  • If the key is found at middle element, the process is terminated.
  • If the key is not found at middle element, choose which half will be used as the next search space.
    • If the key is smaller than the middle element, then the left side is used for next search.
    • If the key is larger than the middle element, then the right side is used for next search.
  • This process is continued until the key is found or the total search space is exhausted.

Binary Search Visualizer

How does Binary Search Algorithm work?

To understand the working of binary search, consider the following illustration:

Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target = 23.

 

The Binary Search Algorithm can be implemented in the following two ways

  • Iterative Binary Search Algorithm
  • Recursive Binary Search Algorithm

Given below are the pseudocodes for the approaches.

Iterative Binary Search Algorithm:

Here we use a while loop to continue the process of comparing the key and splitting the search space in two halves.

C++

// C++ program to implement iterative Binary Search
#include 
using namespace std;

// An iterative binary search function.
int binarySearch(int arr[], int low, int high, int x)
{
    while (low <= high) {
        int mid = low + (high - low) / 2;

        // Check if x is present at mid
        if (arr[mid] == x)
            return mid;

        // If x greater, ignore left half
        if (arr[mid] < x)
            low = mid + 1;

        // If x is smaller, ignore right half
        else
            high = mid - 1;
    }

    // If we reach here, then element was not present
    return -1;
}

// Driver code
int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int x = 10;
    int n = sizeof(arr) / sizeof(arr[0]);
    int result = binarySearch(arr, 0, n - 1, x);
    if(result == -1) cout << "Element is not present in array";
    else cout << "Element is present at index " << result;
    return 0;
}

C

// C program to implement iterative Binary Search
#include 

// An iterative binary search function.
int binarySearch(int arr[], int low, int high, int x)
{
    while (low <= high) {
        int mid = low + (high - low) / 2;

        // Check if x is present at mid
        if (arr[mid] == x)
            return mid;

        // If x greater, ignore left half
        if (arr[mid] < x)
            low = mid + 1;

        // If x is smaller, ignore right half
        else
            high = mid - 1;
    }

    // If we reach here, then element was not present
    return -1;
}

// Driver code
int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 10;
    int result = binarySearch(arr, 0, n - 1, x);
   if(result == -1) printf("Element is not present in array");
   else printf("Element is present at index %d",result);

}

Java

// Java implementation of iterative Binary Search

import java.io.*;

class BinarySearch {
  
    // Returns index of x if it is present in arr[].
    int binarySearch(int arr[], int x)
    {
        int low = 0, high = arr.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;

            // Check if x is present at mid
            if (arr[mid] == x)
                return mid;

            // If x greater, ignore left half
            if (arr[mid] < x)
                low = mid + 1;

            // If x is smaller, ignore right half
            else
                high = mid - 1;
        }

        // If we reach here, then element was
        // not present
        return -1;
    }

    // Driver code
    public static void main(String args[])
    {
        BinarySearch ob = new BinarySearch();
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
        int result = ob.binarySearch(arr, x);
        if (result == -1)
            System.out.println(
                "Element is not present in array");
        else
            System.out.println("Element is present at "
                               + "index " + result);
    }
}

Python

# Python3 code to implement iterative Binary
# Search.


# It returns location of x in given array arr
def binarySearch(arr, low, high, x):

    while low <= high:

        mid = low + (high - low) // 2

        # Check if x is present at mid
        if arr[mid] == x:
            return mid

        # If x is greater, ignore left half
        elif arr[mid] < x:
            low = mid + 1

        # If x is smaller, ignore right half
        else:
            high = mid - 1

    # If we reach here, then the element
    # was not present
    return -1


# Driver Code
if __name__ == '__main__':
    arr = [2, 3, 4, 10, 40]
    x = 10

    # Function call
    result = binarySearch(arr, 0, len(arr)-1, x)
    if result != -1:
        print("Element is present at index", result)
    else:
        print("Element is not present in array")

C#

// C# implementation of iterative Binary Search
using System;

class GFG {
    
    // Returns index of x if it is present in arr[]
    static int binarySearch(int[] arr, int x)
    {
        int low = 0, high = arr.Length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;

            // Check if x is present at mid
            if (arr[mid] == x)
                return mid;

            // If x greater, ignore left half
            if (arr[mid] < x)
                low = mid + 1;

            // If x is smaller, ignore right half
            else
                high = mid - 1;
        }

        // If we reach here, then element was
        // not present
        return -1;
    }

    // Driver code
    public static void Main()
    {
        int[] arr = { 2, 3, 4, 10, 40 };
        int n = arr.Length;
        int x = 10;
        int result = binarySearch(arr, x);
        if (result == -1)
            Console.WriteLine(
                "Element is not present in array");
        else
            Console.WriteLine("Element is present at "
                              + "index " + result);
    }
}

JavaScript

// Program to implement iterative Binary Search

// A iterative binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1

function binarySearch(arr, x)
{
    let low = 0;
    let high = arr.length - 1;
    let mid;
    while (high >= low) {
        mid = low + Math.floor((high - low) / 2);

        // If the element is present at the middle
        // itself
        if (arr[mid] == x)
            return mid;

        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
            high = mid - 1;

        // Else the element can only be present
        // in right subarray
        else
            low = mid + 1;
    }

    // We reach here when element is not
    // present in array
    return -1;
}

arr = new Array(2, 3, 4, 10, 40);
x = 10;
n = arr.length;
result = binarySearch(arr, x);
if (result == -1)
    console.log("Element is not present in array")
    else
    {
        console.log("Element is present at index "
                    + result);
    }

PHP


// PHP program to implement
// iterative Binary Search

// An iterative binary search 
// function
function binarySearch($arr, $low, 
                      $high, $x)
{
    while ($low <= $high)
    {
        $mid = $low + ($high - $low) / 2;

        // Check if x is present at mid
        if ($arr[$mid] == $x)
            return floor($mid);

        // If x greater, ignore
        // left half
        if ($arr[$mid] < $x)
            $low = $mid + 1;

        // If x is smaller, 
        // ignore right half
        else
            $high = $mid - 1;
    }

    // If we reach here, then 
    // element was not present
    return -1;
}

// Driver Code
$arr = array(2, 3, 4, 10, 40);
$n = count($arr);
$x = 10;
$result = binarySearch($arr, 0, 
                       $n - 1, $x);
if(($result == -1))
echo "Element is not present in array";
else
echo "Element is present at index ", 
                            $result;

?>

 

Output

Element is present at index 3

Time Complexity: O(log N)
Auxiliary Space: O(1)

Recursive Binary Search Algorithm:

Create a recursive function and compare the mid of the search space with the key. And based on the result either return the index where the key is found or call the recursive function for the next search space.

C++

#include 
using namespace std;

// A recursive binary search function. It returns
// location of x in given array arr[low..high] is present,
// otherwise -1
int binarySearch(int arr[], int low, int high, int x)
{
    if (high >= low) {
        int mid = low + (high - low) / 2;

        // If the element is present at the middle
        // itself
        if (arr[mid] == x)
            return mid;

        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, low, mid - 1, x);

        // Else the element can only be present
        // in right subarray
        return binarySearch(arr, mid + 1, high, x);
    }
  return -1;
}

// Driver code
int main()
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int query = 90;
    int n = sizeof(arr) / sizeof(arr[0]);
    int result = binarySearch(arr, 0, n - 1, query);
    if (result == -1) cout << "Element is not present in array";
    else cout << "Element is present at index " << result;
    return 0;
}

C

// C program to implement recursive Binary Search
#include 

// A recursive binary search function. It returns
// location of x in given array arr[low..high] is present,
// otherwise -1
int binarySearch(int arr[], int low, int high, int x)
{
    if (high >= low) {
        int mid = low + (high - low) / 2;

        // If the element is present at the middle
        // itself
        if (arr[mid] == x)
            return mid;

        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, low, mid - 1, x);

        // Else the element can only be present
        // in right subarray
        return binarySearch(arr, mid + 1, high, x);
    }

    // We reach here when element is not
    // present in array
    return -1;
}

// Driver code
int main()
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 10;
    int result = binarySearch(arr, 0, n - 1, x);
    if (result == -1) printf("Element is not present in array");
    else printf("Element is present at index %d", result);
    return 0;
}

Java

// Java implementation of recursive Binary Search
class BinarySearch {

    // Returns index of x if it is present in arr[low..
    // high], else return -1
    int binarySearch(int arr[], int low, int high, int x)
    {
        if (high >= low) {
            int mid = low + (high - low) / 2;

            // If the element is present at the
            // middle itself
            if (arr[mid] == x)
                return mid;

            // If element is smaller than mid, then
            // it can only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, low, mid - 1, x);

            // Else the element can only be present
            // in right subarray
            return binarySearch(arr, mid + 1, high, x);
        }

        // We reach here when element is not present
        // in array
        return -1;
    }

    // Driver code
    public static void main(String args[])
    {
        BinarySearch ob = new BinarySearch();
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
        int result = ob.binarySearch(arr, 0, n - 1, x);
        if (result == -1)
            System.out.println(
                "Element is not present in array");
        else
            System.out.println(
                "Element is present at index " + result);
    }
}

Python

# Python3 Program for recursive binary search.


# Returns index of x in arr if present, else -1
def binarySearch(arr, low, high, x):

    # Check base case
    if high >= low:

        mid = low + (high - low) // 2

        # If element is present at the middle itself
        if arr[mid] == x:
            return mid

        # If element is smaller than mid, then it
        # can only be present in left subarray
        elif arr[mid] > x:
            return binarySearch(arr, low, mid-1, x)

        # Else the element can only be present
        # in right subarray
        else:
            return binarySearch(arr, mid + 1, high, x)

    # Element is not present in the array
    else:
        return -1


# Driver Code
if __name__ == '__main__':
    arr = [2, 3, 4, 10, 40]
    x = 10
    
    # Function call
    result = binarySearch(arr, 0, len(arr)-1, x)
    
    if result != -1:
        print("Element is present at index", result)
    else:
        print("Element is not present in array")

C#

// C# implementation of recursive Binary Search
using System;

class GFG {

    // Returns index of x if it is present in
    // arr[low..high], else return -1
    static int binarySearch(int[] arr, int low, int high, int x)
    {
        if (high >= low) {
            int mid = low + (high - low) / 2;

            // If the element is present at the
            // middle itself
            if (arr[mid] == x)
                return mid;

            // If element is smaller than mid, then
            // it can only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, low, mid - 1, x);

            // Else the element can only be present
            // in right subarray
            return binarySearch(arr, mid + 1, high, x);
        }

        // We reach here when element is not present
        // in array
        return -1;
    }

    // Driver code
    public static void Main()
    {

        int[] arr = { 2, 3, 4, 10, 40 };
        int n = arr.Length;
        int x = 10;

        int result = binarySearch(arr, 0, n - 1, x);

        if (result == -1)
            Console.WriteLine(
                "Element is not present in arrau");
        else
            Console.WriteLine("Element is present at index "
                              + result);
    }
}

JavaScript

// JavaScript program to implement recursive Binary Search

// A recursive binary search function. It returns
// location of x in given array arr[low..high] is present,
// otherwise -1
function binarySearch(arr, low, high, x)
{
    if (high >= low) {
        let mid = low + Math.floor((high - low) / 2);

        // If the element is present at the middle
        // itself
        if (arr[mid] == x)
            return mid;

        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, low, mid - 1, x);

        // Else the element can only be present
        // in right subarray
        return binarySearch(arr, mid + 1, high, x);
    }

    // We reach here when element is not
    // present in array
    return -1;
}

let arr = [ 2, 3, 4, 10, 40 ];
let x = 10;
let n = arr.length
let result = binarySearch(arr, 0, n - 1, x);
if (result == -1)
    console.log("Element is not present in array");
else
    console.log("Element is present at index " + result);

PHP


// PHP program to implement
// recursive Binary Search

// A recursive binary search
// function. It returns location
// of x in given array arr[low..high] 
// is present, otherwise -1
function binarySearch($arr, $low, $high, $x)
{
if ($high >= $low)
{
        $mid = ceil($low + ($high - $low) / 2);

        // If the element is present 
        // at the middle itself
        if ($arr[$mid] == $x) 
            return floor($mid);

        // If element is smaller than 
        // mid, then it can only be 
        // present in left subarray
        if ($arr[$mid] > $x) 
            return binarySearch($arr, $low, 
                                $mid - 1, $x);

        // Else the element can only 
        // be present in right subarray
        return binarySearch($arr, $mid + 1, 
                            $high, $x);
}

// We reach here when element 
// is not present in array
return -1;
}

// Driver Code
$arr = array(2, 3, 4, 10, 40);
$n = count($arr);
$x = 10;
$result = binarySearch($arr, 0, $n - 1, $x);
if(($result == -1))
echo "Element is not present in array";
else
echo "Element is present at index ",
                            $result;
                          
?>

 

Output

Element is present at index 3
  • Time Complexity:
    • Best Case: O(1)
    • Average Case: O(log N)
    • Worst Case: O(log N)
  • Auxiliary Space: O(1), If the recursive call stack is considered then the auxiliary space will be O(logN).
  • Binary search can be used as a building block for more complex algorithms used in machine learning, such as algorithms for training neural networks or finding the optimal hyperparameters for a model.
  • It can be used for searching in computer graphics such as algorithms for ray tracing or texture mapping.
  • It can be used for searching a database.
  • Binary search is faster than linear search, especially for large arrays.
  • More efficient than other searching algorithms with a similar time complexity, such as interpolation search or exponential search.
  • Binary search is well-suited for searching large datasets that are stored in external memory, such as on a hard drive or in the cloud.
  • The array should be sorted.
  • Binary search requires that the data structure being searched be stored in contiguous memory locations.
  • Binary search requires that the elements of the array be comparable, meaning that they must be able to be ordered.

Comprehensive Guide to Binary Search Algorithm

What is Binary Search Algorithm?

Binary Search is a highly efficient search algorithm used to find the position of a target value within a sorted array. It leverages the array’s sorted nature to halve the search space after each comparison, reducing the time complexity to O(log N).

Conditions for Applying Binary Search

  1. Sorted Data Structure: The array or data structure must be sorted, either in ascending or descending order.
  2. Constant Time Access: Access to any element in the data structure should take constant time, i.e., random access is possible.

How Binary Search Algorithm Works

  1. Initialize: Start with two pointers, low and high, pointing to the first and last index of the array.
  2. Find Midpoint: Calculate the middle index, mid = low + (high - low) / 2.
  3. Compare: Compare the middle element with the target value:
    • If the middle element equals the target, the search is successful.
    • If the target is less than the middle element, narrow the search to the left half.
    • If the target is greater, narrow the search to the right half.
  4. Repeat: Repeat the process until the target is found or the search space is exhausted.

Binary Search Example

Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91} and a target value of 23.

  1. Set low = 0 and high = 9.
  2. Calculate mid = 4. The middle element is 16.
  3. Since 23 > 16, update low = 5.
  4. Recalculate mid = 7. The middle element is 56.
  5. Since 23 < 56, update high = 6.
  6. Recalculate mid = 5. The middle element is 23. Target found!

Implementation of Binary Search Algorithm

1. Iterative Binary Search

C++ Code

int binarySearch(int arr[], int low, int high, int x) {
while (low <= high) {
int mid = low + (high – low) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x) low = mid + 1;
else high = mid – 1;
}
return -1;
}

Python Code

def binarySearch(arr, low, high, x):
while low <= high:
mid = low + (high – low) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid – 1
return -1

2. Recursive Binary Search

C++ Code

int binarySearch(int arr[], int low, int high, int x) {
if (high >= low) {
int mid = low + (high – low) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] > x) return binarySearch(arr, low, mid – 1, x);
return binarySearch(arr, mid + 1, high, x);
}
return -1;
}

Python Code

def binarySearch(arr, low, high, x):
if high >= low:
mid = low + (high – low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, low, mid-1, x)
else:
return binarySearch(arr, mid + 1, high, x)
return -1

Time Complexity

  • Best Case: O(1) when the middle element is the target.
  • Average and Worst Case: O(log N) as the search space is halved each step.

Advantages of Binary Search

  1. Fast and Efficient: Significantly faster than linear search, especially for large datasets.
  2. Low Space Complexity: Iterative implementation has O(1) space complexity.

Disadvantages of Binary Search

  1. Requires Sorted Data: The data structure must be sorted.
  2. Non-Contiguous Memory Requirement: Works best with data in contiguous memory locations.

Frequently Asked Questions (FAQs)

1. What is Binary Search?

Binary search is an efficient search method for finding a target value within a sorted array by repeatedly halving the search space.

2. How does Binary Search work?

It compares the target with the middle element and decides which half to continue searching based on the comparison.

3. What is the time complexity of Binary Search?

The time complexity is O(log N), where N is the number of elements in the array.

4. What are the prerequisites for Binary Search?

The array must be sorted, and elements must be comparable.

5. Can Binary Search be used on non-numeric data?

Yes, it can be used on any data type as long as there is a defined order, such as strings in alphabetical order.

Binary search is a fundamental algorithm that underpins many complex algorithms and data structures, making it a crucial tool for developers and computer scientists.

Thiru Venkatam: Thiru Venkatam is a distinguished digital entrepreneur and online publishing expert with over a decade of experience in creating and managing successful websites. He holds a Bachelor's degree in English, Business Administration, Journalism from Annamalai University and is a certified member of Digital Publishers Association. The founder and owner of multiple reputable platforms - leverages his extensive expertise to deliver authoritative and trustworthy content across diverse industries such as technology, health, home décor, and veterinary news. His commitment to the principles of Expertise, Authoritativeness, and Trustworthiness (E-A-T) ensures that each website provides accurate, reliable, and high-quality information tailored to a global audience.
Related Post