Reputation: 851
It doesn't seem too hard to get the max value:
int getMax(int arr[], int size) {
if(size == 1) {
return arr[0]
}
return max(arr[size - 1], getMaxIndex(arr, size - 1));
}
But how can I find the index of where it was at? If I create a count variable it will just get wiped as soon I recursively call. I can't find anywhere online where someone does this recursively with only the array and a size parameter. Thanks for any help.
Upvotes: 1
Views: 995
Reputation: 217408
You might do it like that:
int getMaxIndex(int arr[], int size) {
if (size == 1) {
return 0;
}
const auto recMaxIndex = getMaxIndex(arr, size - 1);
if (arr[recMaxIndex] < arr[size - 1]) {
return size - 1;
} else {
return recMaxIndex;
}
}
Upvotes: 5