Arrays December 27 ,2025

Binary Search on Arrays

Binary Search is a highly efficient searching algorithm used to find the position of a target element in a sorted array or monotonic search space. Instead of scanning elements one by one, Binary Search repeatedly divides the search space into halves, reducing the time complexity to O(log N).

Binary Search works by comparing the target value with the middle element of the array:

  • If the middle element equals the target → search ends.
  • If the target is smaller → search continues in the left half.
  • If the target is larger → search continues in the right half.

This divide-and-conquer strategy makes Binary Search much faster than linear search for large datasets.

To successfully apply Binary Search:

  1. The data structure must be sorted (ascending or descending).
  2. Random access to elements should be possible (array or array-like structure).
  3. The comparison operation must take constant time.

Binary Search Algorithm (Step-by-Step)

  1. Initialize two pointers:
    • low = 0
    • high = n - 1
  2. Find the middle index:

    mid = low + (high - low) / 2
    
  3. Compare arr[mid] with the target value.
  4. Based on comparison:
    • If equal → return index
    • If smaller → search right half
    • If larger → search left half
  5. Repeat until the element is found or the search space is exhausted.

Example

Array:
arr = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}

Target: 23

Binary Search will:

  • Start from middle → 16
  • Move right
  • Reach 23 → element found

Binary Search can be implemented in two ways:

  1. Iterative Binary Search
  2. Recursive Binary Search

Iterative Binary Search Algorithm

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

This approach uses a loop and does not consume extra stack memory.

C++ Implementation

#include 
#include 
using namespace std;

int binarySearch(vector& arr, int x) {
    int low = 0, high = arr.size() - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == x)
            return mid;
        else if (arr[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }

    return -1;
}

int main() {
    vector arr = {2, 3, 4, 10, 40};
    int x = 10;

    int result = binarySearch(arr, x);

    if (result == -1)
        cout << "Element not found";
    else
        cout << "Element found at index " << result;

    return 0;
}

C Implementation

#include 

int binarySearch(int arr[], int n, int x) {
    int low = 0, high = n - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == x)
            return mid;
        else if (arr[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }

    return -1;
}

int main() {
    int arr[] = {2, 3, 4, 10, 40};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 10;

    int result = binarySearch(arr, n, x);

    if(result == -1)
        printf("Element not found");
    else
        printf("Element found at index %d", result);

    return 0;
}

Java Implementation

class BinarySearch {

    static int binarySearch(int[] arr, int x) {
        int low = 0, high = arr.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;

            if (arr[mid] == x)
                return mid;
            else if (arr[mid] < x)
                low = mid + 1;
            else
                high = mid - 1;
        }

        return -1;
    }

    public static void main(String[] args) {

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

        int result = binarySearch(arr, x);

        if(result == -1)
            System.out.println("Element not found");
        else
            System.out.println("Element found at index " + result);
    }
}

Python Implementation

def binary_search(arr, x):

    low = 0
    high = len(arr) - 1

    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


arr = [2, 3, 4, 10, 40]
x = 10

result = binary_search(arr, x)

if result == -1:
    print("Element not found")
else:
    print("Element found at index", result)

C# Implementation

using System;

class BinarySearch {

    static int Search(int[] arr, int x) {

        int low = 0, high = arr.Length - 1;

        while (low <= high) {

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

            if (arr[mid] == x)
                return mid;
            else if (arr[mid] < x)
                low = mid + 1;
            else
                high = mid - 1;
        }

        return -1;
    }

    static void Main() {

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

        int result = Search(arr, x);

        if(result == -1)
            Console.WriteLine("Element not found");
        else
            Console.WriteLine("Element found at index " + result);
    }
}

JavaScript Implementation

function binarySearch(arr, x) {

    let low = 0;
    let high = arr.length - 1;

    while (low <= high) {

        let mid = Math.floor(low + (high - low) / 2);

        if (arr[mid] === x)
            return mid;
        else if (arr[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }

    return -1;
}

let arr = [2, 3, 4, 10, 40];
let x = 10;

let result = binarySearch(arr, x);

if(result === -1)
    console.log("Element not found");
else
    console.log("Element found at index " + result);

PHP Implementation


Output

Element found at index 3

 

Recursive Binary Search Algorithm

Recursive Binary Search uses the divide-and-conquer technique.
Instead of using a loop, the algorithm calls itself recursively, reducing the search space by half in each call until the target element is found or the range becomes invalid.

How Recursive Binary Search Works

  1. Find the middle index of the current search range.
  2. Compare the middle element with the target value.
  3. If they are equal, return the index.
  4. If the target is smaller, recursively search the left subarray.
  5. If the target is larger, recursively search the right subarray.
  6. If the range becomes invalid (low > high), return -1.

C Implementation

#include 

int binarySearch(int arr[], int low, int high, int x) {

    if (low <= high) {

        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;
}

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 not found");
    else
        printf("Element found at index %d", result);

    return 0;
}

Java Implementation

class RecursiveBinarySearch {

    static int binarySearch(int[] arr, int low, int high, int x) {

        if (low <= high) {

            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;
    }

    public static void main(String[] args) {

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

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

        if(result == -1)
            System.out.println("Element not found");
        else
            System.out.println("Element found at index " + result);
    }
}

Python Implementation

def binary_search(arr, low, high, x):

    if low <= high:

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

        if arr[mid] == x:
            return mid

        elif arr[mid] > x:
            return binary_search(arr, low, mid - 1, x)

        else:
            return binary_search(arr, mid + 1, high, x)

    return -1


arr = [2, 3, 4, 10, 40]
x = 10

result = binary_search(arr, 0, len(arr) - 1, x)

if result == -1:
    print("Element not found")
else:
    print("Element found at index", result)

C# Implementation

using System;

class RecursiveBinarySearch {

    static int BinarySearch(int[] arr, int low, int high, int x) {

        if (low <= high) {

            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;
    }

    static void Main() {

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

        int result = BinarySearch(arr, 0, arr.Length - 1, x);

        if(result == -1)
            Console.WriteLine("Element not found");
        else
            Console.WriteLine("Element found at index " + result);
    }
}

JavaScript Implementation

function binarySearch(arr, low, high, x) {

    if (low <= high) {

        let mid = Math.floor(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;
}

let arr = [2, 3, 4, 10, 40];
let x = 10;

let result = binarySearch(arr, 0, arr.length - 1, x);

if(result === -1)
    console.log("Element not found");
else
    console.log("Element found at index " + result);

PHP Implementation

 $x)
            return binarySearch($arr, $low, $mid - 1, $x);

        return binarySearch($arr, $mid + 1, $high, $x);
    }

    return -1;
}

$arr = [2, 3, 4, 10, 40];
$x = 10;

$result = binarySearch($arr, 0, count($arr) - 1, $x);

if($result == -1)
    echo "Element not found";
else
    echo "Element found at index ".$result;

?>

Output

Element found at index 3

Complexity Analysis

CaseTime Complexity
Best CaseO(1)
Average CaseO(log N)
Worst CaseO(log N)

Auxiliary Space:

  • Iterative: O(1)
  • Recursive: O(log N)
  • Searching in sorted arrays
  • Finding first/last occurrence
  • Rotated sorted arrays
  • Database indexing (B-Trees)
  • Version control debugging (git bisect)
  • Machine learning hyperparameter tuning
  • Competitive programming optimization problems
  • Square Root of an Integer
  • First and Last Position in Sorted Array
  • Count 1’s in a Sorted Binary Array
  • Search in Rotated Sorted Array
  • Minimum Element in Rotated Array

Next Blog-
Two Pointers Technique

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Array Memo...
Arrays December 12 ,2025

Array Memory Represe...

Array Oper...
Arrays December 12 ,2025

Array Operations and...

Advantages...
Arrays December 12 ,2025

Advantages and Disad...

Arrays in...
Arrays December 12 ,2025

Arrays in C

Vector in...
Arrays December 12 ,2025

Vector in C++ STL

Arrays vs...
Arrays December 12 ,2025

Arrays vs ArrayList...

JavaScript...
Arrays December 12 ,2025

JavaScript Arrays

Two Pointe...
Arrays January 01 ,2026

Two Pointers Techniq...

Prefix Sum...
Arrays January 01 ,2026

Prefix Sum Technique

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com