So, basically, I have never ever seen an example of a recursive function that takes only an array as its sole parameter and somehow manages to recursively return the index of its minimum element (if the minimum is repeated, the lowest index containing the minimum is returned). I suspect that this is not possible, and that at least one parameter would be required, namely, the size of the array. Am I right? Or is it actually possible!
Note: My lab professor seems to have assigned us several homework problems that lack any parameter for the size or index or a recursive function taking an array as one of its parameters. Depending on the input here I will search for a way to do so, or else, to complete the assignments in question by adding the necessary parameters.
Arrays decay to pointers, so yes you probably do need an extra parameter for size.
Unless the size is a hard-coded and you may take it for granted, e.g.:
1 2 3 4 5 6 7 8 9 10 11 12 13
constint SIZE = 40;
// or
#define SIZE 40
// later ...
int array[SIZE];
int zero(int *pi)
{
for (int i=0; i < SIZE; ++i)
pi[i] = 0;
}
You can write two overload functions. One that you will call in program will have one parameter of type reference to array. The other that will be called internally from the first one will have two parameters - pointer and the size of the arrray
For example (without testing)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template <typename T>
size_t min_element( const T *a, size_t n )
{
if ( n == 1 ) return ( 0 );
n = min_element( a + 1, n - 1 );
return ( a[n+1] < a[0] ? n + 1 : 0 );
}
template <typename T, size_t N>
size_t min_element( const T ( &a )[N] )
{
return ( min_element( a, N ) );
}
Arrays can have only one element but your program will ignore such arrays. In the assignment there is said that the function must return an index of the minimal element not the minimal element itself.
Okay, guys, I appreciate the help... In my desperation I tried this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int index = 0;
int getMin(double arr[]) {
int min;
if(index == 0) {
min = index;
}
else {
if(arr[index] < min) {
min = index;
}
}
getMin(arr[++index]);
return min;
}
But it won't compile.... Note: I'm coding for a linux environment and it allows me to call the index of an array via a variable. Still having a lot of trouble with this... It's down to the wire and I was doing so well in my class until this homework!