I need help with this Java problem to output as it's explained in this image below: import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; public class LabProgram { static public int recursions = 0; static public int comparisons = 0; private static ArrayList readNums(Scanner scnr) { int size = scnr.nextInt(); ArrayList nums = new ArrayList(); for (int i = 0; i < size; ++i) { nums.add(scnr.nextInt()); } return nums; } static public int binarySearch(int target, ArrayList integers, int lower, int upper) { recursions+=1; int index = (lower+upper)/2; comparisons+=1; if(target == integers.get(index)){ return index; } if(lower == upper){ comparisons+=1; if(target == integers.get(lower)){ return lower; } else{ return -1; } } else{ comparisons+=1; if(integers.get(index) > target){ return binarySearch(target,integers,lower,index-1); } else{ return binarySearch(target,integers,index + 1,upper); } } } public static void main(String [] args) { Scanner scnr = new Scanner(System.in); ArrayList integers = readNums(scnr); 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); System.out.println(); } }
I need help with this Java problem to output as it's explained in this image below:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class LabProgram {
static public int recursions = 0;
static public int comparisons = 0;
private static ArrayList<Integer> readNums(Scanner scnr) {
int size = scnr.nextInt();
ArrayList<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < size; ++i) {
nums.add(scnr.nextInt());
}
return nums;
}
static public int binarySearch(int target, ArrayList<Integer> integers, int lower, int upper) {
recursions+=1;
int index = (lower+upper)/2;
comparisons+=1;
if(target == integers.get(index)){
return index;
}
if(lower == upper){
comparisons+=1;
if(target == integers.get(lower)){
return lower;
}
else{
return -1;
}
}
else{
comparisons+=1;
if(integers.get(index) > target){
return binarySearch(target,integers,lower,index-1);
}
else{
return binarySearch(target,integers,index + 1,upper);
}
}
}
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<Integer> integers = readNums(scnr);
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);
System.out.println();
}
}
Trending now
This is a popular solution!
Step by step
Solved in 4 steps with 2 images