DSA-Bootcamp-Java icon indicating copy to clipboard operation
DSA-Bootcamp-Java copied to clipboard

Uisng Binary approach to solve Array Index Out of Bounds exception in Infinite Binary search to decrease time complexity

Open Arsh164 opened this issue 1 year ago • 0 comments

`public class BinarySearchInfiniteArray { public static void main(String[] args) { int[] array={3,5,7,9,10,90,100,130,140,160,170}; int target=10; int ans=infinitesearch(array,target); System.out.println(ans); }

public static int infinitesearch(int[] arr, int target) {
    int i = 0;
    int f = 0;
    int l = 0;
    // Using try catch to for catching Array Index out of index exception
    try {

        while (true) {
            f = l + 1;
            l = l + 2 ^ i;
            while (f <= l) {

                int mid = f + (l - f) / 2;
                if (arr[mid] < target) {
                    f = mid + 1;

                } else if (arr[mid] > target) {
                    l = mid - 1;
                } else {
                    return mid;
                }
                i++;
            }
        }

    } catch (ArrayIndexOutOfBoundsException exception) {
        //Resolving it to find the last index of array
        int temp = f;
        boolean error = false;
        int mid = 0;
        while (!error) // Till the last index is not found
        {
            //Uisng Binary Search approach to find the last index of array
            try {
                mid = f + (f - l) / 2;
                f = mid;
                if (f == l) //Point where the last array is found
                {
                    error = true;
                }
            } catch (ArrayIndexOutOfBoundsException exception1) //Exception When mid is out of bounds
            {
                l = mid;
            }
        }
        //Last index of array is Found 
        f = temp;
        while (f <= l) {

            mid = f + (l - f) / 2;
            if (arr[mid] < target) {
                f = mid + 1;

            } else if (arr[mid] > target) {
                l = mid - 1;
            } else {
                return mid;
            }


        }

    }
    return -1;// If target element is not present
}

} `

Arsh164 avatar Jan 27 '24 16:01 Arsh164