Friday, February 28, 2014

Recursion

There are a few principles in computer science that never fail to astonish me, one being recursion.  I was intrigued from the first time I heard Professor Heap mention the concept.   The reason I found it fascinating is because I had not expected the existence of a sneaky method as such that so cleverly uses the idea of a problem within a problem.  Recursion is the term given to the method used to solve one bigger problem by systematically approaching the solutions of smaller instances of that problem.   In other words, recursion occurs when a function calls itself a number of times until it reaches the solution it seeks.  One may think of this approach as a close relative of mathematical induction.  The beauty of this method is that it follows our own way of thinking; we like to break problems into smaller, more manageable parts.

A key to designing a successful recursive method is to include a base case; a condition to stop recursion hence preventing it from going to infinity.  Using the following example, it is easy to understand that function “get_factorial” uses itself to return the n factorial of consecutive numbers until it reaches the number 0, which is the termination condition.

 Having used the principle myself, I can say that there are both positives and negatives to this approach.  Recursion is often a preference by many programmers as it makes code clearer, simpler and more “elegant”.  Although recursion may be easier to handle, especially with transversing trees from the human end, I find that it is generally slower and takes more stacks and hence memory than more standard means of computing.  All in all, it seems that the nature of the problem eventually determines the most ideal method of computing.

No comments:

Post a Comment