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


LinkBack URL
About LinkBacks
Reply With Quote
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: