Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Java Please , make BinarySearch and nBinarySearch work. Currently, it can't find the position of the element. public class RecursiveBinarySearch { //Recursive call public static

Java

Please , make BinarySearch and nBinarySearch work. Currently, it can't find the position of the element.

public class RecursiveBinarySearch { //Recursive call public static int BinarySearch(int[] v, int key) { int low = 0; int high = v.length - 1; return BinarySearch(v, key, low, high); } //Recursive call public static int BinarySearch(int[] v, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; int mid = (low + high) / 2; if (key < v[mid]) return BinarySearch(v, key, low, mid - 1); else if (key == v[mid]) return mid; else return BinarySearch(v, key, mid + 1, high); } //Non-recursive call public static int nBinarySearch(int arr[], int key) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; // Check if x is present at mid if (arr[m] == key) return m; // If x greater, ignore left half if (arr[m] < key) l = m + 1; // If x is smaller, ignore right half else r = m - 1; } // if we reach here, then element is not present return -1; } public static void main(String[] args) { // Fill an integer array of 1000 multiples of 3 from 0 to 2997 // (i.e., 0, 3, 6, 9,,2997) and have them properly sorted. System.out.println(" Fill an integer array of 1000 multiples of 3 from 0 to 2997 and have them properly sorted"); int[] array = new int[1000]; Arrays.setAll(array, j -> j*3); System.out.println(Arrays.toString(array)); for (int j = 0; j < array.length; j++) { //Arrays.sort(array); System.out.println(" Using recursive call element " + array[j] + " is present at index " + BinarySearch(array, j)); System.out.println("Using non-recursive call element " + array[j] + " is present at index " + nBinarySearch(array, j));

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Microsoft SQL Server 2012 Unleashed

Authors: Ray Rankins, Paul Bertucci

1st Edition

0133408507, 9780133408508

More Books

Students also viewed these Databases questions