Question
How is the number of searches 5 for this java binary search? n n // Java implementation of recursive Binary Search n class RecursiveBinarySearch {
How is the number of searches 5 for this java binary search?
n n// Java implementation of recursive Binary Search
n class RecursiveBinarySearch {
n private static int count = 0;
n // Returns index of x if it is present in arr[L...R], else return -1
n int binarySearch(int arr[], int L, int R, int x) {
n ++count;
n if (R >= L) {
n int mid = L + (R - L) / 2;
n
n if (arr[mid] == x) { // If the element is present at the middle itself
n return mid;
n }
n
n // If element is smaller than mid, then it can only be present in left subarray // mid is too high
n if (x < arr[mid]) {
n return binarySearch(arr, L, mid - 1, x);
n }
n
n return binarySearch(arr, mid + 1, R, x); // Else, element is n bigger than mid, the element can only be present in right subarray // n mid is too low
n }
n
n return -1; // We reach here when element is not present in the array
n }
n
n /////////////////////////////////////////////////////////////////////////////////////////////
n public static void main(String[] args) {
n RecursiveBinarySearch thisClass = new RecursiveBinarySearch();
n 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
n // int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}; // 21 elements
n int arraySize = arr.length;
n int x = 67;
n int result = thisClass.binarySearch(arr, 0, arraySize - 1, x);
n
n if (result == -1) {
n System.out.println("Element not present");
n }
n else {
n System.out.println("Element found at index " + result);
n }
n
n System.out.println("Number of searches: " + count);
n }
n }
Step by Step Solution
3.51 Rating (185 Votes )
There are 3 Steps involved in it
Step: 1
The value of count will be 5 after the execution of the code because that is the number of times the binarySearch method was called The binarySearch method is called recursively until the element bein...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