GeeksforGeeks » Miscellaneous
Recursion help!!
(3 posts)-
int Max(int a[],int n) { int max; if(n==1) return a[0]; else max=Max(a,n-1); if(max>a[n-1]) return max; else return a[n-1]; }Hi, the above is a code to find the max in an array recursively. I find very difficult in understanding the flow of recursive programs. Can someone help me out in explaining the flow of the program with stack sections if possible.
Thanks!! -
The link http://www.cs.umd.edu/class/spring2002/cmsc214/Tutorial/trace-recursion.html might be helpful
-
int Max(int a[],int n) { int max; if(n==1) -------------------------------------------------------( 1 ) return a[0]; else max=Max(a,n-1); -------------------------------------------------------( 2 ) if(max>a[n-1]) return max; -------------------------------------------------------( 3 ) } else return a[n-1]; -------------------------------------------------------( 4 ) }Statement (1) will executed when there is only single present in the array
Statement (2) otherwise else part will executed
in this section we calling same function with array index n,n-1,......,0
(position of the elements)Statement (3) checking whether this present element is larger than previous
one ie here we are comparing ( n )th and
(n-1) th element; if (n) th is greater then it will return its valueStatement (4)
here if (n-1) th is greater so it will return its valueSource: http://groups.google.co.in/group/algogeeks/browse_thread/thread/626f2cc928c7b68e
Reply
You must log in to post.