How is the number of searches 5 for this java binary search? n n // Java implementation
Question:
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 }
Accounting Business Reporting for Decision Making
ISBN: 9780730302414
4th edition
Authors: Jacqueline Birt, Keryn Chalmers, Albie Brooks, Suzanne Byrne, Judy Oliver