package java_programs;
import java.util.*;

public class FIND_FIRST_IN_SORTED {
    public static int find_first_in_sorted(int[] arr, int x) {
        int lo = 0;
        int hi = arr.length - 1;

        while (lo <= hi) {
            int mid = (lo + hi) / 2; 

            if (x == arr[mid] && (mid == 0 || x != arr[mid-1])) {
                return mid;
            } else if (x < arr[mid]) {
                hi = mid - 1;
            } else {
                lo = mid + 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        // Define test cases
        int[][] testArrays = {
            {1, 2, 2, 3, 4}, // Multiple occurrences of the target
            {1, 1, 1, 1, 1}, // All elements same as the target
            {1, 2, 3, 4, 5}, // Single occurrence of the target
            {5, 6, 7, 8, 9}, // Target not present
            {}, // Empty array
            {2}, // Single element equal to the target
            {3}  // Single element, target not present
        };

        int[] targets = {2, 1, 3, 1, 2, 2, 2}; // targets for each test array
        int[] expectedResults = {1, 0, 2, -1, -1, 0, -1}; // expected results

        // Run tests
        boolean allTestsPassed = true;
        for (int i = 0; i < testArrays.length; i++) {
            int result = find_first_in_sorted(testArrays[i], targets[i]);
            if (result != expectedResults[i]) {
                allTestsPassed = false;
                System.out.println("Test failed:");
                System.out.println("Array: " + Arrays.toString(testArrays[i]));
                System.out.println("Target: " + targets[i]);
                System.out.println("Expected index: " + expectedResults[i]);
                System.out.println("Received index: " + result);
                System.out.println();
            }
        }

        if (allTestsPassed) {
            System.out.println("All tests passed.");
        }
    }
}