More Exercises

Binary search- recursively

public class Main {
    //wrapper function
    public static int binarySearch(int[] arr, int x) {
        int result = bSearch(arr, 0, arr.length - 1, x);
        if (result == -1)
            System.out.println("Element not present");
       return result;
    }

    // Recursive function: Returns index of element or -1 if not found
    public static int bSearch(int[] arr, int l, int r, int x) {
        if (r >= l && l < arr.length-1) {
            int mid = l + (r - l) / 2;

            if (arr[mid] == x)  // If the element is in the middle
                return mid;

            if (arr[mid] > x) //elem is smaller than middle elem
                return bSearch(arr, l, mid - 1, x);
            else             //elem is larger than middle elem
                return bSearch(arr, mid + 1, r, x);
        }

        return -1;  //not present in array
    }

    public static void main(String args[]) {
        int arr[] = { 2, 4, 8, 16, 50 };
        int x = 16;
        int res = binarySearch(arr, x);
        System.out.println(res);
    }
}

Exercise - Replace

Solution

notice here

we start substring from from.length()

and here

we start substring from 1

Last updated

Was this helpful?