largest element in an array using recursion?

May 2, 2019 at 10:16am
Can you help me about write largest element in an array using recursion?
I found this can you explain me?
And I wish the smallesT
Many thanks to all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

int max(int *array, int n)
{
int maxs;
if (n==1) return array[0]; 
if (n==2)
{
if (array[0]>array[1]) 
return array[0];
else return array[1];
}
maxs = max(&array[1],n-1); 
if (array[0]>maxs)
return array[0];
else return maxs;
Last edited on May 2, 2019 at 10:18am
May 2, 2019 at 10:42am
I found this
Where did you find it? There was no elucidation enclosed?
May 2, 2019 at 10:49am
> if (n==1) return array[0];
Do you understand why this is necessary?

Your n==2 is just a waste of code.

All recursion falls into essentially two cases.

A base case that is trivially solvable, like for example
- the height of an empty tree
- the length of an empty list, array, string
- the max (or min, or sum, or whatever) of an array with only one element.

And a recursive step which involves some trivial computation based on the 'current' value, and one or more recursive calls.
May 2, 2019 at 10:57am
So it is wrong?
Can you help me with a simple working code?
May 2, 2019 at 11:53am
> Can you help me with a simple working code?
And when your next assignment comes along, you're back here begging again.

Because you really only had a superficial understanding based on just reading some words.

You NEED to put that code into a compilable program, and run the code through the debugger and step through the code one line at a time.

Print all the variables, examine the stack to see how many recursive calls have been made.
In other words, apply yourself to some effort to understand.

May 2, 2019 at 12:40pm
1
2
3
4
template <typename T> T maximum( T *a, int n )
{
   return n == 1 ? *a : max( *a, maximum( a + 1, n - 1 ) );
}
Last edited on May 2, 2019 at 12:40pm
Topic archived. No new replies allowed.