Question
How is the number of searches 5 for this java binary search? // Java implementation of recursive Binary Search class RecursiveBinarySearch { private static int
How is the number of searches 5 for this java binary search?
// Java implementation of recursive Binary Search class RecursiveBinarySearch { private static int count = 0; // Returns index of x if it is present in arr[L...R], else return -1 int binarySearch(int arr[], int L, int R, int x) { ++count; if (R >= L) { int mid = L + (R - L) / 2; if (arr[mid] == x) { // If the element is present at the middle itself return mid; } // If element is smaller than mid, then it can only be present in left subarray // mid is too high if (x < arr[mid]) { return binarySearch(arr, L, mid - 1, x); } return binarySearch(arr, mid + 1, R, x); // Else, element is bigger than mid, the element can only be present in right subarray // mid is too low } return -1; // We reach here when element is not present in the array } ///////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { RecursiveBinarySearch thisClass = new RecursiveBinarySearch(); int arr[] = {2, 3, 4, 10, 24, 33, 35, 36, 37, 40, 43, 56, 61, 64, 67, 72, 75, 83, 90, 95, 100}; // 21 elements // int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}; // 21 elements int arraySize = arr.length; int x = 67; int result = thisClass.binarySearch(arr, 0, arraySize - 1, x); if (result == -1) { System.out.println("Element not present"); } else { System.out.println("Element found at index " + result); } System.out.println("Number of searches: " + count); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started