There are different approches to solve problems in programming. One is the iterative approche and the other the recursive one.
Let us look at a commonly known function, the factorial function, for example 6! which is 6*5*4*3*2*1=720. An iterative algorithm in Java would look like this:
int iterative(int n) {
int res = 1;
for (int i = 2; i <= n; i++) {
res *= i;
}
return res;
}
And this is the recursive solution:
int recursive (int n) {
if (n == 0) {
return 1;
}
return n * recursive(n – 1);
}
Both algorithms will do the same job, but they are doing it in a very different way. While the iterative one is using a loop, the recursive one is calling itself again and again and so consuming more and more stack space, which is uneconomical. So why should we use recursive algorithms at all?
Recursive algorithms are much faster than iterative algorithms in searching and sorting data structures, especially if they are dynamic structures. The bigger the amount of data, the faster they are, but also the bigger the wasting of memory.