128k views
2 votes
Write a recursive method named binarySearch that accepts a sorted array of integers and an integer target value and uses a recursive binary search algorithm to find and return an index at which that target value is found in the array. If the target value is not found in the array, return -1. The following code shows some example calls and their expected return values: // index 0 1 2 3 4 5

User YK S
by
4.9k points

1 Answer

7 votes

Answer:

10

-1

Process finished with exit code 0

Explanation: see code bellow

public class BinarySearchRecursive {

public static int binarySearch(int[] a, int key) {

return binarySearchRecursiveHelper(a, key, 0, a.length - 1);

}

public static int binarySearchRecursiveHelper(int[] arr, int target, int start, int end) {

if (start > end) {

return -1;

}

int mid = (start + end) / 2;

if (arr[mid] == target) {

return mid;

} else if (target < arr[mid]) {

return binarySearchRecursiveHelper(arr, target, start, mid - 1);

} else {

return binarySearchRecursiveHelper(arr, target, mid + 1, end);

}

}

public static void main(String[] args) {

int[] a = {-4, 2, 7, 10, 15, 20, 22, 25, 30, 36, 42, 50, 56, 68, 85, 92, 103};

int index = binarySearch(a, 42); // 10

System.out.println(index);

index = binarySearch(a, 66); // -1

System.out.println(index);

}

}

User Sieppl
by
4.5k points