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

replace("world", "or", "") -> wrl
replace("python program python program", "python", "java") -> java program java program

Solution

public class Main {
    public static String replace(String str, String from, String to){
        if (str.length() < from.length() ) //don't need to check anymore
            return str;

        if (str.startsWith(from))
            return to + replace(str.substring(from.length()), from, to);
        else //if doesnt start with
            return str.charAt(0) + replace(str.substring(1), from, to);
    }

    public static void main(String[] args) {
        System.out.println(replace("world", "or", ""));
        System.out.println(replace("world", "or", "ZZZ"));
        System.out.println(replace("i am a python program i am a python program", "python", "java"));
    }
}
wld
wZZZld
i am a java program i am a java program

notice here

if (str.startsWith(from))
            return to + replace(str.substring(from.length()), from, to);

we start substring from from.length()

and here

else
     return str.charAt(0) + replace(str.substring(1), from, to);

we start substring from 1

Last updated