We don't always prefer recursion to while/for loops. We prefer recusion when it fits the model of the problem we are trying to solve. Problems that can be easily broken down into a repeated sub-problem are often more efficiently/easily written through recursion. Other problems are better suited for iterative (loops) solutions.
Have a look at my source for a more clear explanation.
2006-12-30 03:48:19
·
answer #1
·
answered by Chris 2
·
1⤊
0⤋
When calculating the time complexity of an algorithm, recursion is usually faster than loops. What actually happens is that you trade memory space (recursive functions push into the stack) for time. If you have heard of Big O notation, it will explain this a lot better. For example, A linear bubble sort, which is just a doubly nested loop, has a time complexity of O(N^2), where a merge sort is O(N*log N).
Sometimes it takes less code using recursion than loops also. However, there are cases where loops are better than recusion. It really depends on the problem.
2006-12-30 11:58:30
·
answer #2
·
answered by Joe 4
·
0⤊
0⤋
We don't usually. IMHO, recursive iterations should be reserved for times when memory is plentiful compared to the maximum number of times the storage will be allocated to a new function's variables, when execution speed overrides that consideration and when a gracefull bail out is achievable and acceptable. Otherwise, again IMHO, a well done while or for loop is every bit as fast in the user's eyes and more reliable in possible runtime error situations. In other words, it is a valid tool to choose in some rare cirumstances; but like the infamous goto, should probably be avoided where possible.
2006-12-30 12:02:50
·
answer #3
·
answered by griz803 5
·
0⤊
1⤋
In addition, recursion is more efficient in situations where while/for loops can take up many more lines of code using more CPU processing cycles than it needs to.
[UPDATE]
dlucf said exactly what I was getting at in more detail...
2006-12-30 11:58:33
·
answer #4
·
answered by SirCharles 6
·
0⤊
0⤋