https://leanpub.com/discretemathematicalalgorithmanddatastructures
The advantage of using recursion is its shortness, cleanliness, and moreover, it is closer to our discrete mathematical definitions. If you think and model your code keeping the mathematical conceptions in your mind, then recursion is close to your definition.
It is more evident when we use recursion in finding the Fibonacci series. Mathematically, the Fibonacci is defined as the following:
Fibonacci of 1 or 2 is 1
Fibonacci of F (for F > 2) is Fibonacci of (F - 1) + Fibonacci of (F – 2)
If we want to find the Fibonacci series using recursion, it is not only the simplest version, but also mathematically similar.
Watch the next line of code snippet.
package fun.sanjibsinha.recursive;
public class AlgoFibTwo {
static int getFibonacci(int f) {
if ((f == 1) || (f == 2)){
return 1;
} else {
return (getFibonacci(f - 1) + getFibonacci(f - 2));
}
}
public static void main(String[] args) {
int newNumber = 6, result;
result = getFibonacci(newNumber);
System.out.printf("Fibonacci series of " + newNumber + " = " + result);
System.out.printf("");
System.out.printf("");
}
}
//output of the above code
Fibonacci series of 6 = 8
We can do the same thing using iterative way, but it does not reflect the mathematical conception as the recursion does. The next code snippet shows us the same thing.
package fun.sanjibsinha.recursive;
public class AlgoFibOne {
static int getFibinacci(int f) {
int k1, k2, k3;
k1 = k2 = k3 = 1;
for (int j = 3; j <= f; j++) {
k3 = k1 + k2;
k1 = k2;
k2 = k3;
}
return k3;
}
public static void main(String[] args) {
int newNumber = 6, result;
result = getFibinacci(newNumber);
System.out.printf("Fibonacci series of " + newNumber + " = " + result);
System.out.printf("");
System.out.printf("");
}
}
//output of the above code
Fibonacci series of 6 = 8
Ability to simulate the mathematical models cannot always give the moral support to the recursions. Because there are many other factors while we program, we need to keep them in our mind.
Maintaining that the recursive versions are slower than the iterative versions, we may still want to adopt it for some reasons. When the code is heavy in iterative versions, it is much simpler to adopt the recursions, it also easier to debug and maintain. Whatever our reasons to adopt the recursions, slowing down the program may cost at the end.
We cannot save the memory space, we cannot speed up the execution; yet, in some cases, recursions are essential.
As we progress, we will find that later.