Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary Search #1

Merged
merged 2 commits into from
Oct 3, 2024
Merged

Binary Search #1

merged 2 commits into from
Oct 3, 2024

Conversation

Ansari-Shamaila
Copy link
Owner

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

}

@Ansari-Shamaila Ansari-Shamaila merged commit a151deb into Ansari-Shamaila:main Oct 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant