Question
Pleas help me fix the the code below in Java so that: if the input are:9 1 2 3 4 5 6 7 8 9
Pleas help me fix the the code below in Java so that:
if the input are:9 1 2 3 4 5 6 7 8 9 2 --> Output are : index: 1, recursions: 2, comparisons: 3
if the input are: 9 11 22 33 44 55 66 77 88 99 11 --> The output are: index: 0, recursions: 3, comparisons: 5
if the input are: 9 11 22 33 44 55 66 77 88 99 99 --> The output are: index: 8, recursions: 4, comparisons: 7 .
if the input are: 8 10 15 20 25 30 35 40 45 50 --> The output are: index: -1, recursions: 4, comparisons: 7
And final requirement: Test binarySearch() with [10, 20, 20, 20, 20, 20, 25, 30, 35, 40, 45, 50, 60] and target 20. Should return 2.
Thank you very much! I really need the result correct with exactly output above if the input like above! Thank you.
Belove are my code that need to be fixed:
import java.util.Scanner; import java.util.ArrayList; import java.util.Collections;
public class LabProgram { // Read and return an ArrayList of integers. private static ArrayList
static int recursions = 0; static int comparisons = 0;
static public int binarySearch(int target, ArrayList
// Base case: search area is empty if (lower > upper) { return -1; }
int index = (lower + upper) / 2;
// Base case: target found if (integers.get(index) == target) { ++comparisons; return index; }
// Recursive case: search left half if (integers.get(index) > target) { // Increment comparisons counter comparisons+=2; return binarySearch(target, integers, lower, index - 1); }
// Recursive case: search right half // Increment comparisons counter comparisons+=2; return binarySearch(target, integers, index + 1, upper); }
public static void main(String [] args) { Scanner scnr = new Scanner(System.in); // Input a list of integers ArrayList
// Input a target value for the search int target = scnr.nextInt();
int index = binarySearch(target, integers, 0, integers.size() - 1);
System.out.printf("index: %d, recursions: %d, comparisons: %d ", index, recursions, comparisons); } }
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