0

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 28, 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?

2
  • 2
    std::max does the comparison. Commented Oct 17, 2016 at 20:50
  • Think about what happens when you call this function with an array that has only one element. Simple, right? Then think about what happens when you call it with an array that has two elements. Then three, then four, etc. Commented Oct 17, 2016 at 21:11

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.