Answered step by step
Verified Expert Solution
Question
1 Approved Answer
In c + + please!! 1 5 . 1 4 LAB: Binary search Binary search can be implemented as a recursive algorithm. Each call makes
In c please!! 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 function BinarySearch with the following specifications:
Parameters:
a target integer
a vector of integers
lower and upper bounds within which the recursive call will search
Return value:
the index within the vector where the target is located
if target is not found
The template provides the main program and a helper function that reads a vector from input.
The algorithm begins by choosing an index midway between the lower and upper bounds.
If target integers.atindex return index
If lower upper, return to indicate not found
Otherwise call the function recursively on half the vector parameter:
If integers.atindex target, search the vector from index to upper
If integers.atindex target, search the vector from lower to index
The vector 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 vector. Note: lower upper should not be counted.
Hint: Use a global variable to count calls and comparisons.
The input of the program consists of:
the number of integers in the vector
the integers in the vector
the target to be located
Ex: If the input is:
the output is:
index: recursions: comparisons:
qxzqy
Instructor note:
Line here uses notation from C as opposed to C printf is the C equivalent of using the cout function in C
The "translated" line would look like:
cout "index: index recursions: recursions comparisons: comparisons endl; #include
#include
#include
using namespace std;
Read integers from input and store them in a vector.
Return the vector.
vector ReadIntegers
int size;
cin size;
vector integerssize;
for int i ; i size; i Read the numbers
cin integers.ati;
sortintegersbegin integers.end;
return integers;
int BinarySearchint target, vector integers, int lower, int upper
Type your code here.
int main
int target;
int index;
vector integers ReadIntegers;
cin target;
index BinarySearchtarget integers, integers.size;
printfindex: d recursions: d comparisons: d
index, recursions, comparisons;
return ;
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