Recursion Questions

int maxSubArraySum(int arr[], int l, int h)
{
// Base Case: Only one element
if (l == h)
return arr[l];

// Find middle point
int m = (l + h)/2;

return max(maxSubArraySum(arr, l, m),
maxSubArraySum(arr, m+1, h),
maxCrossingSum(arr, l, m, h));

Question on the order C++ processes this function
will the first recursion(maxSubArraySum(arr, l, m)) go until it completes or will the function run through each recursion once then repeat.
will the first recursion(maxSubArraySum(arr, l, m)) go until it completes or will the function run through each recursion once then repeat.
I don't understand the question.
First, what do you mean by "first recursion"? What's "a recursion"?
Second, repeat what? How could anything be repeated when there's no iteration?
the function calls itself 3 times, splits the array into left and right halves over and over until the length is 1. so it repeats depending on size of array.

My question is what order is calls itself

return(maxSubArraySum(arr, l, m),
maxSubArraySum(arr, m+1, h),
maxCrossingSum(arr, l, m, h));

I am envisioning a tree with two parent and each child is the left and right half of the left and right half of each array until the length is 1. I'm just not sure the order the compiler runs it.
-------------*1 ------------------- *2
-------- *3------*4 ----------- *5--- *6
--------*7-*8--*9*10-------*11*12--*13*14

basically will it run 1,3,7,8,4,9,10,2,5,11,12,6,13,14
or 1,2,3,4,5,6,7,8..



Last edited on
The comma operator evaluates the expressions from left to right. Note that only the result of the last expression is returned. See:

https://en.cppreference.com/w/cpp/language/operator_other
[Built-in comma operator]
Post maxCrossingSum.
int maxCrossingSum(int arr[], int l, int m, int h)
{
// Include elements on left of mid.
int sum = 0;
int left_sum = INT_MIN;
for (int i = m; i >= l; i--)
{
sum = sum + arr[i];
if (sum > left_sum)
left_sum = sum;
}

// Include elements on right of mid
sum = 0;
int right_sum = INT_MIN;
for (int i = m+1; i <= h; i++)
{
sum = sum + arr[i];
if (sum > right_sum)
right_sum = sum;
}

// Return sum of elements on left and right of mid
return left_sum + right_sum;
}
thanks coder777, appreciate it
Topic archived. No new replies allowed.