Question
Can u please Modify the function in the codebelow so that it returns a bool value indicating whether a match was found. Add a reference
Can u please Modify the function in the codebelow so that it returns a bool value indicating whether a match was found. Add a reference parameter pos, which is set to the location of the match if the search was successful. If a match was not found, set pos to the index of the next larger value instead, or to the array size if the target value is larger than all the elements of the array.
#include #include #include
using namespace std;
/** Finds an element in a sorted array. @param a the sorted array with the elements to search @param from the start of the range to search @param to the end of the range to search @param value the value to search for @return the index of the first match, or -1 if not found */ int binary_search(int a[], int from, int to, int value) { if (from > to) { return -1; }
int mid = (from + to) / 2; if (a[mid] == value) { return mid; } else if (a[mid] < value) { return binary_search(a, mid + 1, to, value); } else { return binary_search(a, from, mid - 1, value); } }
int main() { srand(time(0)); const int SIZE = 20; int values[SIZE]; values[0] = 0; for (int i = 1; i < SIZE; i++) { values[i] = values[i - 1] + rand() % 10; cout << values[i] << " "; } cout << endl;
bool done = false; while (!done) { cout << "Enter number to search for, -1 when done: "; int target; cin >> target; if (target == -1) { done = true; } else { int pos = binary_search(values, 0, SIZE - 1, target); cout << "Found in position " << pos << endl; } } return 0; }
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