what is wrong with this code?
Here’s how we do it. Assume our array is already sorted. Imagine our array with indexes low to
high. We’re searching for our target value. We will point to the midpoint index in the array.
array[]
low mid high
● If array[m] == target, return that index. We’ve found it!
● If array[m] < target, recursively search from index mid + 1 to high.
● If array[m] > target, recursively search from index low to mid - 1.
int iAns = binary_search(iList, 0, 5, 17);
// int dAns = binary_search(dList, 0, 5, 18.9);
// int cAns = binary_search(cList, 0, 5, 'c');
cout << "Integer answer at index " << iAns << endl;
// cout << "Double answer at index " << dAns << endl;
// cout << "Char answer at index " << cAns << endl;
return 0;
}
------------
main file is fine and should remain untouched. It is a project in school, teacher provides the main file. My problem is I dont know what goes in the arguments of return binary_search(.....)
You also need to return the index, not the target value.
You fail to take any action if the target is NOT found. In the code below I have set the return index to -1 in this case (and you should check it with an appropriate test case in main().
#pragma once
//This program will recursively search through arrays to find the target index
template <class T > int binary_search( T array[], int low, int high, T target ) // <==== just T target
{
if ( low > high ) return -1; // <==== necessary if target NOT found
int midpointIndex;
midpointIndex = ( low + high ) / 2;
if (array[midpointIndex] == target)
{
return midpointIndex; // <==== return the index, not the value
}
elseif ( array[midpointIndex] < target )
{
return binary_search( array, midpointIndex + 1, high, target ); // <==== argument just NAME of array
}
else
{
return binary_search( array, low, midpointIndex - 1, target ); // <==== ditto
}
}