Recursive or iterative algorithms?

In general, which is more useful and efficent in algorithms? I feel a recusive algorithm would be much more memory intesive because of its constant re-calling of automatically allocated variables, but im interested in other opinions. Thanks!
Recursive algorithms are better for problems that are better solved using recursive algorithms and iterative algorithms are better for problems that are better solved using iterative algorithms.
When there are both recursive and iterative algorithms of similar complexity, prefer the iterative variant.
Last edited on
One problem with recursive solutions is that, if you're recursing on the stack, you have a) a limit on the complexity of problems you can solve with that program, and b) no way of knowing exactly how much more recursive steps the program can handle without crashing.
b) is the bigger problem. a) is a problem or not depending on how big each recursive step is, and on the specifics of the algorithm. For example, Quick Sort in only 40 recursive steps can sort 1 TiB of data.
My take on it is that if there are 2 equivalent algorithms where one is recursive and the other is iterative then always take the iterative approach because there's less overhead in the function calls and you don't have to worry about the stack space. Keep in mind that generally, only tail recursive algorithms have an iterative equivalent algorithm.
I agree with ssrun, and off course with helios and athar, that whenever required recursive are good, Till the time you keep your recursive solution with prevention of infinite recursion, it will cause not much harm... And as famous in programming world that iteration is for machine and recursion is for programmer, so make suitable as per needs. but if possible just go for iterative approach.
Topic archived. No new replies allowed.