Binary Search Approach

When searching for a number in an array binary search is an algorithm that takes advantage of the sorted nature of the array. It does this by reducing the search space by half, in each iteration.

Steps to solve the problem:

  • Start by setting two pointers, “low” and “high ” to the last indices of the array
  • Calculate the middle index using the formula low+( high-low) / 2.
  • Compare the element at the index with the target value.
  • If they match, return the index as it indicates that we have found our target.
  • If the middle element is greater than the target value update “high” to be one less than “middle.”
  • If the middle element is less than the target value update “low” to be one more than “middle.”
  • Repeat steps 2-6 until either “low” becomes greater, than “high“. We find our target.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

int binarySearch(int arr[], int left, int right, int target)
{
    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (arr[mid] == target) {
            return mid;
        }

        if (arr[mid] < target) {
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }
    return -1;
}

// Drivers code
int main()
{
    int arr[] = { 10, 20, 30, 40, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 30;

    int index = binarySearch(arr, 0, n - 1, target);

    if (index != -1) {
        cout << "Target found at index " << index << endl;
    }
    else {
        cout << "Target not found in the array." << endl;
    }

    return 0;
}
Java
// Java code for the above approach:

class GFG {

    static int binarySearch(int arr[], int left, int right,
                            int target)
    {
        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
                return mid;
            }

            if (arr[mid] < target) {
                left = mid + 1;
            }
            else {
                right = mid - 1;
            }
        }

        return -1;
    }

    // Drivers code
    public static void main(String[] args)
    {
        int arr[] = { 10, 20, 30, 40, 50 };
        int n = arr.length;
        int target = 30;

        int index = binarySearch(arr, 0, n - 1, target);

        if (index != -1) {
            System.out.println("Target found at index "
                               + index);
        }
        else {
            System.out.println(
                "Target not found in the array.");
        }
    }
}

// This code is contributed by ragul21
Python
def binary_search(arr, left, right, target):
    while left <= right:
        mid = left + (right - left) // 2

        if arr[mid] == target:
            return mid

        if arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return -1

# Driver code
arr = [10, 20, 30, 40, 50]
n = len(arr)
target = 30

index = binary_search(arr, 0, n - 1, target)

if index != -1:
    print("Target found at index {}".format(index))
else:
    print("Target not found in the array.")
C#
using System;

class BinarySearchExample
{
    // Function to perform binary search on a sorted array
    static int BinarySearch(int[] arr, int left, int right, int target)
    {
        while (left <= right)
        {
            int mid = left + (right - left) / 2;

            // If target is found, return the index
            if (arr[mid] == target)
            {
                return mid;
            }

            // If target is greater, ignore the left half
            if (arr[mid] < target)
            {
                left = mid + 1;
            }
            // If target is smaller, ignore the right half
            else
            {
                right = mid - 1;
            }
        }
        // Target not found
        return -1;
    }

    // Driver code
    static void Main()
    {
        int[] arr = { 10, 20, 30, 40, 50 };
        int n = arr.Length;
        int target = 30;

        // Perform binary search
        int index = BinarySearch(arr, 0, n - 1, target);

        // Display the result
        if (index != -1)
        {
            Console.WriteLine($"Target found at index {index}");
        }
        else
        {
            Console.WriteLine("Target not found in the array.");
        }
    }
}
Javascript
// Function to perform binary search on a sorted array
function binarySearch(arr, left, right, target) {
    // Continue the search until the left pointer is less than or equal to the right pointer
    while (left <= right) {
        // Calculate the middle index of the current search range
        let mid = Math.floor(left + (right - left) / 2);

        // If the middle element is equal to the target, return its index
        if (arr[mid] === target) {
            return mid;
        }

        // If the middle element is less than the target, update the left pointer
        // to search in the right half of the array
        if (arr[mid] < target) {
            left = mid + 1;
        } 
        // If the middle element is greater than the target, update the right pointer
        // to search in the left half of the array
        else {
            right = mid - 1;
        }
    }

    // If the target is not found, return -1
    return -1;
}

// Driver code
let arr = [10, 20, 30, 40, 50];
let n = arr.length;
let target = 30;

// Call the binarySearch function to find the index of the target in the array
let index = binarySearch(arr, 0, n - 1, target);

// Display the result based on whether the target was found or not
if (index !== -1) {
    console.log("Target found at index " + index);
} else {
    console.log("Target not found in the array.");
}
//This Code is contributed by Prachi

Output
Target found at index 2





Time Complexity: O(log n) The time complexity of search is O(log n) when the array is sorted.
Auxiliary space: O(1) because we are using constant memory.

Find the Target number in an Array

Finding a number within an array is an operation, in the field of computer science and data analysis. In this article, we will discuss the steps involved and analyze their time and space complexities.

Examples:

Input: Array: {10, 20, 30, 40, 50} , Target: 30
Output: “Target found at index 2”

Input: Array: {10, 20, 30, 40, 50}, Target: 40
Output: “Target found at index 3”

Similar Reads

Linear Search Approach:

The basic idea to find a number in an array involves going through each element of the array one by one, and comparing them with the target value until a match is found....

Binary Search Approach:

When searching for a number in an array binary search is an algorithm that takes advantage of the sorted nature of the array. It does this by reducing the search space by half, in each iteration....

Hashing Approach:

Hashing is an approach that employs a hash function to map elements in an array to locations, within a data structure, usually known as a hash table. When you have an urgent need to locate a number this method proves to be highly effective....