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

Define a function bool search(int nums[], int length, int target, int & first, i

ID: 3649174 • Letter: D

Question

Define a function bool search(int nums[], int length, int target, int & first, int & last) that sets 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 { 1, 2, 2, 2, 4, 7} then search( nums, 6, 2,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 the 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). Use linear search to locate the first occurence of target, then continue scanning to locate the last occurence.

Explanation / Answer

please rate - thanks

remember - 1 is true, 0 is false

#include <iostream>
using namespace std;
bool search(int[], int, int, int &, int &) ;
int main()
{int nums[]= { 1, 2, 2, 2, 4, 7} ;
bool result;
int first=-1,last=-1;
result=search( nums, 6, 2,first, last);
cout<<"results of search( nums, 6, 2,first, last) ";
cout<<"returned value = "<<result<<" first= "<<first<<" last= "<<last<<endl;
first=-1;
last=-1;
result=search (nums, 6, 5, first, last);
cout<<"results of search (nums, 6, 5, first last) ";
cout<<"returned value = "<<result<<" first= "<<first<<" last= "<<last<<endl;
system("pause");
return 0;
}
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;

}

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