Logic of Recursion in General
Hello Everyone,
I'm just starting to get into Recursions and Sorting Algorithms and all that jazz, and I'm having a hard time getting my head around the idea of a
method calling itself until a point. Well, I understand that part, but it's simply the syntax I don't get. Specifically, the factorial recursive method.
Code :
public int factorial(int i){
if(i!=1){
return (i * factorial(i-1));
}
else{
return 1;
}
This is the part I don't understand. At some point in time, any integer decreasing will become 1. Doesn't that mean that thiswould always return 1?
It's difficult to explain. Pretend that I'm running the number "3" through this method. 3 is not equal to one, so it continues by multiplying 3 by factorial of (3-1) which is 2. So right now we have 3*2, and 2 is not equal to one, so it also continues by saying 2* factorial of (2-1) which is 1. 1 is equal to 1, so it breaks this "loop" of multiplying by simply returning 1. But what happened to the (3*2) part?It seems like by stating another return statement, that part is discarded, but it is for some reason multiplied by 1.
:/ Any help?
Thanks,
Jake
Re: Logic of Recursion in General
Remember the return mechanism has the previous results remaining on the stack when it finally returns the 1. As the returns are undone, each returned value is multiplied by i and returned to its caller to do the same again.
Re: Logic of Recursion in General
Quote:
Originally Posted by
Norm
Remember the return mechanism has the previous results remaining on the stack when it finally returns the 1. As the returns are undone, each returned value is multiplied by i and returned to its caller to do the same again.
Thanks for the reply! :) Yes, that actually puts what I don't understand in perfect words. How is it that the entire "stack" is returned? The factorial method makes more sense now that you said that, but the recursive call for merge sort is still puzzling me. It goes something like this:
Code :
//In the method static int[] mergeSort()
int[] left = mergeSort()
This is puzzling, because I know that in the end groups of arrays will be returned. However, the return type of the method is a single array. It's slightly mind boggling the fact that an entire "stack" of arrays is returned, rather than just one array. I'm just trying to get my head around that I suppose.
Re: Logic of Recursion in General
Somewhere in the code it will actually merge 2 arrays together.