Skip to content

Binary Search  #754

Description

@Ansari-Shamaila

Optimized version of binary search:---->>
import java.util.Scanner;

public class BinarySearch {

// Binary Search function
public static int binarySearch(int[] arr, int x) {
    int start = 0;
    int end = arr.length - 1;

    while (start <= end) {
        int mid = start + (end - start) / 2;  // To prevent overflow

        if (arr[mid] == x) {
            return mid;  // Element found, return index
        } else if (arr[mid] < x) {
            start = mid + 1;  // Move right
        } else {
            end = mid - 1;  // Move left
        }
    }
    return -1;  // Element not found
}

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    // Input array size
    int n = sc.nextInt();
    int[] arr = new int[n];

    // Input array elements
    for (int i = 0; i < n; i++) {
        arr[i] = sc.nextInt();
    }

    // Input number of test cases
    int t = sc.nextInt();

    // For each test case, perform binary search
    for (int i = 0; i < t; i++) {
        int x = sc.nextInt();  // Element to search
        int result = binarySearch(arr, x);
        System.out.println(result);
    }
}

}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions