Recursion - The human way of solving problems
Recursion can be thought of as the "human way" to solve a problem. While a very useful concept in some respects, recursion is also a controversial topic within computer science. It can be an extremely useful tool for traversing certain data structures, however in many cases, (though not all) it can also be done in more efficient ways with iteration.
Recursion is the process of breaking a larger problem down into subproblems, or smaller versions of itself. This process eventually terminates in what's known as the base case, where the problem can not be simplified any further. There are many problems for which this has useful applications, for instance the towers of hanoi problem may be vastly simplified using recursion. The job of the monks of Hanoi can be vastly simplified by simply breaking the problem of moving a tower of n disks into smaller, simpler cases of moving n-1 disks until finally reaching the base case of moving a single disk.
The problem with recursion comes when efficiency is a concern. This is where it becomes a controversial topic, with some arguing that it generates numerous function calls on the stack. While this argument is true, recursion does create copies of the functions within the stack along with it's associated arguments, it is often the simplest, and in some cases the only realistic way of solving the problem.
At this point it comes down to efficiency vs. simplicity. Which do you prefer? A shorter more readable and sometimes more understandable solution, or a longer, more efficient solution?
Excellent! Can you think of examples where it might be more efficient to use recursion rather than iteration?
ReplyDeleteIt really depends on the language and the implementation.
ReplyDeleteIn python recursion can be extremely inefficient as function calls are more expensive to execute because of the way the call stack works.
Tail recursion in particular can be just as fast as iteration, however it again depends on the language. Python is interpreted so it may still not be faster than iteration, but in some compiled languages, depending on how the compiler is written it can optimize tail recursion when it recognizes it.