Recursion happens in programming when the function itself at least once. So, a recursive function call itself until they find the base case( the value that function knows the result) and then start to close the recursive call until return something meaningful. If a function do not have at least one base, it will generate a infinitive loop, then the program will crash. So, when programmers are creating the structure of a function, they need to be aware of the advantages and consequences of using recursion. One pro is to reduce the code. When programmers write a recursive function, they compact their code, and make it clearly . Another advantages is there are some data structure, such as binary tree or tree that use the recursion in their own concept, so to design the methods to deals with this data structure, for example, find a node in an binary tree. There are, however, some consequences, one of them is to allocate more memory to trace the code. This happens because the recursive function need to call itself until they get into the step that they know the result. Another consequence is many cases, the recursion can take more time to process than a iterative function. There are some program which takes the recursion as a solution, for example, the sum of a list, or the Fibonacci sequence, the binary search. The conclusion of recursion is that every case the programmers must decide which method is better to apply, in many cases, the best solution is recursion.
No comments:
Post a Comment