CowEatsGrass CowEatsGrass - 1 year ago 65
C++ Question

Finding max in an array using recursion

Suppose I have the following declarations:

int arr[5] = {1,10,9,28,3};
int low = 0;
int high = 4;
int largest = findLargest(ar, low, high);

I am suppose to write a "findLargest" function using recursion, and this is what I got

int findLargest(int arr[], int low, int high)

if (low == high)
return arr[low];
return max(arr[low], findLargest(arr, low+1, high));

The output was
, which was expected. However, I don't really understand how does this recursive function "compare" the values. (By that I mean I don't see any operators such as
. The only operator that I see is
). So, how does this recursive function compare the values in the array?

Bim Bim
Answer Source

The recursion is using the std::max function, which uses operator>. The maximum of the subarray [a;b] is the maximum between a and the maximum of the subarray [a + 1;b] (Which is a if a = b).