Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is my code using linear search in a function. bool search(int nums[], int l

ID: 3649287 • Letter: T

Question

This is my code using linear search in a function.
bool search(int nums[], int length, int target, int & first, int & last)
{
int i = 0, j;
while (i <= length)
if (nums[i] == target)
{
first = i;
for (j = i + 1;j <= length;j++)
if (nums[j] != target)
{
last = j - 1;
return true;
}
}
else
i++;
return false;
}


Can you please help me to change to Binary search?
The idea of the function is to set first and last to the indexes of the first and last occurences of target in sorted array nums or leaves them unchanged if there are no occurences. If the target does occur then the function returns true and otherwise false. For example if nums contains:

{ 3, 6, 6, 6, 8, 9}

then search( nums, 6, 6,first, last) will set first to 1 and last to 3 and return true. On the other hand search (nums, 6, 5, first last) will return false and leave first and last unchanged.

The driver will use 5 as te target and output the values of first and last followed by the return value (1 for true, 0 for false). If 5 is not found then first and last will have values -1 (their original values when passed in as arguments by the driver).

Explanation / Answer

#include using namespace std; int binary_search(int *list, int size,int key) { int up_bound=list[size-1]; int low_bound=list[0]; int mid=(up_bound+low_bound)/2; for(int i=0;ilist[mid]) { low_bound=list[mid-1]; mid=(up_bound+low_bound)/2; } else if(key0) { coutkey; int result=binary_search(arr,size,key); if(result==-1) { cout
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote