Question: 1 4 . 3 3 . 1 : LAB: Binary search Binary search can be implemented as a recursive algorithm. Each call makes a recursive
: LAB: Binary search
Binary search can be implemented as a recursive algorithm. Each call makes a recursive call on onehalf of the list the call received as an argument.
Complete the recursive method binarySearch with the following specifications:
Parameters:
a target integeran ArrayList of integerslower and upper bounds within which the recursive call will search
Return value:
the index within the ArrayList where the target is located if target is not found
The template provides main and a helper function that reads an ArrayList from input.
The algorithm begins by choosing an index midway between the lower and upper bounds.
If target integers.getindex return index
If lower upper, return to indicate not found
Otherwise call the function recursively on half the ArrayList parameter:
If integers.getindex target, search the ArrayList from index to upperIf integers.getindex target, search the ArrayList from lower to index
The ArrayList must be ordered, but duplicates are allowed.
Once the search algorithm works correctly, add the following to binarySearch:
Count the number of calls to binarySearch
Count the number of times when the target is compared to an element of the ArrayList. Note: lower upper should not be counted.
Hint: Use a static variable to count calls and comparisons.
The input of the program consists of:
the number of integers in the ArrayList
the integers in the ArrayList
the target to be located
Ex: If the input is:
the output is:
index: recursions: comparisons:
SOLVE USING THIS FORMAT PLEASE
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 readNumsScanner scnr
int size scnrnextInt; Read size of ArrayList
ArrayList nums new ArrayList;
for int i ; i size; i Read the numbers
numsaddscnrnextInt;
return nums;
static public int binarySearchint target, ArrayList integers,
int lower, int upper
Type your code here.
public static void mainString args
Scanner scnr new ScannerSystemin;
Input a list of integers
ArrayList integers readNumsscnr;
Input a target value for the search
int target scnrnextInt;
int index binarySearchtarget integers, integers.size;
System.out.printfindex: d recursions: d comparisons: d
index, recursions, comparisons;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
