简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM