In my college, I was asked to write a JAVA program for Fibonacci series. I used recursion to write that program.
But, the asst lecturer said that my algo is not efficient and asked me to analyze. He added that by convention, iteration is suitable in that program than recursion.
How to analyze our algorithm? How to check the space and time complexity in both iteration and recursion ? Just then, i found that these things are as important as the CORRECTNESS OF A PROGRAM.
If time complexity is the point of focus, and number of recursive calls would be large, it is better to use iteration. However, if time complexity is not an issue and shortness of code is, recursion would be the way to go.
The main difference between these two is that in recursion, we use function calls to execute the statements repeatedly inside the function body, while in iteration, we use loops like “for” and “while” to do the same. Iteration is faster and more space-efficient than recursion.
Recursion uses more memory but is sometimes clearer and more readable. Using loops increases the performance, but recursion can sometimes be better for the programmer (and their performance).
The recursive function runs much faster than the iterative one. The reason is because in the latter, for each item, a CALL to the function st_push is needed and then another to st_pop . In the former, you only have the recursive CALL for each node.
As a thumbrule:
So whenever the number of steps is limited to a small manageable number, you can go for recursion. As you will be confident the stack will never overflow and at the same time recursion code is compact and elegant
.
If you want to explore more these might help. Recursion vs loops and Recursion or Iteration?
Edit As pointed out by @MrP, some special recursions, can be optimized by some compilers.
It doesn't have anything to do with the complexity of the algorithm: when you use recursion - each call creates a new frame on the stack - so if the recursion is too deep you might run into StackOverflow :)
By using iteration - you're running in a loop (potentially) over the same space (overriding the parameter previous values) which is faster as well as more secure from StackOverflow perspective.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With