OneCompiler

Binary Search

104

arr = [ 1,3,5,7,8,10]
##Find the index Where We can insert a new element.
Element we are adding in the above array is not there in the array.

Ans : ( here we will search for the target even though it is not available in the array then l and r will cross each and the final l is the required index .)

class HelloWorld {
    public static int bs(int arr[], int target) {
        int l = 0;
        int r = arr.length - 1;
        while (l <= r) {
            int m = l + (r - l) / 2;
            if (arr[m] > target) {
                r = m - 1;
            } else {
                l = m + 1;
            }
        }
        return l;
    }

    public static void main(String[] args) {
        int arr[] = {1, 3, 5, 7};
        System.out.println(bs(arr, 4));
    }
}

```****