C++: Define a function int binarySearch(int nums[], int length, int target, int
ID: 3566396 • Letter: C
Question
C++: Define a function
int binarySearch(int nums[], int length, int target, int minValue, int maxValue);
That returns the index of any element of nums whose value is between minValue and maxValue, inclusive. If there is no such value then the function should return -1. Assume that nums is in ascending order. For example if minValue is 3 and maxValue is 5, then the function will return the index of a 3, 4 or 5, or it will return -1 if none of those values occur in the array. You do not need to write a lot of code for this; it
Explanation / Answer
int binary_search(int array[],int length,int target,int minValue,int maxValue)
{
int index;
if (minValue > maxValue)
index = -1;
else
{
int mid = (minValue + maxValue)/2;
if (target == array[mid])
index = mid;
else
if (target < array[mid])
index = binary_search(array,length,minValue, mid-1, target);
else
index = binary_search(array,length, mid+1, maxValue, target);
} // end if
return index;
}// end binarySearch
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.