Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages and disadvantages of recursion?

Tags:

recursion

With respect to using recursion over non-recursive methods in sorting algorithms or, for that matter, any algorithm what are its pros and cons?

like image 462
Jeeka Avatar asked Mar 09 '11 18:03

Jeeka


People also ask

What is the advantage of recursion?

Recursion adds clarity and (sometimes) reduces the time needed to write and debug code (but doesn't necessarily reduce space requirements or speed of execution). Reduces time complexity. Performs better in solving problems based on tree structures.

What is recursion write advantages and disadvantages of recursion?

In short and simple terms, a recursive function is one which calls itself. Advantage: It can reduce time complexity and has a relaxation on the number of iterations( we can run a variable number of loops ). It is easy to implement. Disadvantage: It can throw a StackOverflowException since it consumes a lot of memory.

What is recursion What are the advantages and disadvantages of recursion over iteration?

Because the function has to add to the stack with each recursive call and keep the values there until the call is finished, the memory allocation is greater than that of an iterative function. Recursion can be slow. If not implemented correctly (as stated above with memoization) it can be much slower than iteration.


2 Answers

For the most part recursion is slower, and takes up more of the stack as well. The main advantage of recursion is that for problems like tree traversal it make the algorithm a little easier or more "elegant". Check out some of the comparisons:

link

like image 157
cmaynard Avatar answered Sep 21 '22 14:09

cmaynard


Recursion means a function calls repeatedly

It uses system stack to accomplish its task. As stack uses LIFO approach and when a function is called the controlled is moved to where function is defined which has it is stored in memory with some address, this address is stored in stack

Secondly, it reduces a time complexity of a program.

Though bit off-topic,a bit related. Must read. : Recursion vs Iteration

like image 37
Saurabh Gokhale Avatar answered Sep 21 '22 14:09

Saurabh Gokhale