Saturday, February 28, 2015

Slog Week 7: Recursion

Recursion


A recursive function is a function that calls itself until it finds the result. The general expression of a recursion should have two cases, which are a base case, the action to take when it has the result; and a recursive call, that calls the function again when the result is not found. If a recursive function is run without a base case, it will generate an infinitive loop and caused the program to crash.

def f(x):
       if statement:
              return or do something
       else:
              do something
              f(x)

The idea of recursion is interesting, and I think having such a method in programming will be really helpful. At first we do exercise on tracing a recursion, which is not a difficult task, and it helps understand the function a lot. But when I began to write a recursive function, I found it confusing and did not know where to begin with. After I wrote the function, sometimes it did not work simply because it didn’t have a base case so it kept running. However, after the general expression is introduced and I implement recursion based on that, everything gets smooth.


In most of the time recursion is an efficient way to solve a problem since it reduces a lot of code and make the function clear and some data structures such as tree and binary tree that use recursion in its concepts. However, there is also a situation that it is an inefficient to use recursion because it may visit more stuff and takes more time than simply using an iterative function.

No comments:

Post a Comment