Wednesday, February 26, 2014

Recursion: When and Why?

Recursion is a strong technique of programming where a function calls itself to finish a task. Recursion requires two important parts: the base case and the recursive case. The base case is the one that prevents recursion from going on infinitely. On the other hand, the recursive case is the recursive technique where the function calls itself to solve a problem multiple times until the base case is reached. 

When should recursion be used and when should it not be used? In programming, sometimes there are problems where the large problem at hand can be broken down into a collection of the same problem, but at a smaller scale. For example, the Towers of Hanoi for 3 pegs is a problem where a stack of items must be moved from the source to the destination. This must all be done while following the rule that no bigger piece can ever go on top of a smaller piece. As a result, there exists a sequence of moves that move each item to an intermediate location and then later moving it to the destination. These same moves are repeatedly done over and over again for each item of the stack of items. Hence, in the big picture, the task of moving the large stack of items is just the processing of moving each item piece by piece. This is the recursive technique used in the towers of Hanoi. For problems similar to the towers of Hanoi, the number of times the main recursive technique is used is usually unknown to the coder. Thus, by using recursion the coder can make the program apply this recursive technique as much times as required until the base case is met, which stops the program from executing further. Thus, recursion should be used when the number of iterations required is unknown to the coder.


Another reason why a coder would use recursion is for more elegant code, which makes it easier to read for the coder and the user. This is because the alternative to using recursion is using loops to iterate, which requires more code to achieve the same process as recursion in some complicated scenarios. Also, another thing to take note is that sometimes this results in much messier code. From my understanding of recursion, I believe that recursion makes problems easier for cases such as nested lists, trees, linked lists and any format that has a smaller version of itself within itself. I can conclude that mastering this strong technique will simplify future code and make recursive problems easier to understand in the future.

1 comment:

  1. Who: KeLin
    What: Learned more about recursion
    When:March 5
    How: recursively read your post...

    ReplyDelete