Question: In Java, please help me to fix this. ----------------------------------------------------- My code: import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; public class LabProgram { // Read and return

In Java, please help me to fix this.

In Java, please help me to fix this. ----------------------------------------------------- My code: import

-----------------------------------------------------

My code:

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 readNums(Scanner scnr) { int size = scnr.nextInt(); // Read size of ArrayList ArrayList nums = new ArrayList(); for (int i = 0; i

static int recursions = 0; static int comparisons = 0;

static public int binarySearch(int target, ArrayList integers, int lower, int upper) { ++recursions; // Increment recursions counter int index = (lower + upper) / 2;

// Base case: target found if (integers.get(index) == target) { ++comparisons; return index; }

// Base case: search area is empty if (lower >= upper) { return -1; }

// 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 integers = readNums(scnr);

// 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); } }

Output differs. See highlights below. Input Your output Expected output

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!