Recursion is:
- A way of thinking about problems.
- A method for solving problems.
- Related to mathematical induction.
A method is recursive if it can call itself; either directly:void f() {
... f() ...
}
or indirectly:void f() {
... g() ...
}
void g() {
... f() ...
}
You might wonder about the following issues:
Q: Does using recursion usually make your code faster?
A: No.Q: Does using recursion usually use less memory?
A: No.
Q: Then why use recursion?
A: It sometimes makes your code much simpler!
One way to think about recursion:
- When a recursive call is made, the method clones itself, making new copies of:
- the code
- the local variables (with their initial values),
- the parameters
- Each copy of the code includes a marker indicating the current position. When a recursive call is made, the marker in the old copy of the code is just after the call; the marker in the "cloned" copy is at the beginning of the method.
- When the method returns, that clone goes away, but the previous ones are still there, and know what to execute next because their current position in the code was saved (indicated by the marker).
EmoticonEmoticon