Why is recursion better than iteration




















You will get the idea that it is plain hard to solve DFS with iteration. Another good thing to try out : Try to write Merge sort iteratively. It will take you quite some time. Trust me. Try to write your own version to solve depth-first search iteratively. You will notice that some problems are easier to solve it recursively. Hint : Recursion is good when you are solving a problem that can be solved by divide and conquer technique.

Python Javascript Linux Cheat sheet Contact. The main reasons to use recursion are that it's more intuitive in many cases when it mimics our approach of the problem that some data structures like trees are easier to explore using recursion or would need stacks in any case Of course every recursion can be modeled as a kind of loop : that's what the CPU will ultimately do. Is it correct to say that everywhere recursion is used a for loop could be used?

Consider tail recursion , and read the "Lambda: The Ultimate Tony Hoare originally described Quicksort iteratively, and he reported that it was very difficult to explain. See Quicksort in Haskell for the details.

If the array has length equal to one, you are finished, otherwise, you actually have to sort it. First, you pick a pivot element.

Traditionally, this is the first element, but any element can be used. Next, you take a pass over the array, to form three subarrays. The first is all elements less than the pivot, the second is all elements equal to the pivot, and the third is all elements greater than the pivot.

If the array element values are required to be unique, then the length of the second subarray is equal to one. Now quicksort the first subarray, and then quicksort the second subarray. Binary search is easiest to understand when presented recursively, and it is in fact tail-recursive.

You probe the middle element of the array. If it is equal to the value you are looking for, you are done. If the middle element is greater than the value you seek, then you know that the desired value must lie "to the left", and you search the subarray before the middle element, otherwise you search the subarray after the middle element.

In both cases, you know that the middle element is not the target, so you leave it out. You either find your target, or you run out of array to search. At that point, you bail all the way out, and you're done.

In the year , never mind , any self-respecting compiler knows how to do tail recursion optimization, even Java compilers. Note: The classic Java virtual machine does not support general tail call optimization, for lack of a general GOTO operation, but that does not affect tail recursion optimization. The real problem, a lot of places, is that the people running the show never learned about tail recursion optimization, and so they ban all recursion.

I ran into this at Nortel Networks, and had to write a full page of comments explaining it and some related concepts AND show them the assembly language listings that proved the compiler was NOT actually generating recursive calls.

Nortel is gone now, but those managers still exist in a lot of places. Sign up to join this community. The best answers are voted up and rise to the top. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Learn more. With recursion, you also get the added benefit that other programmers can more easily understand your code — which is always a good thing to have.

Correcting other answers: any iteration can be transformed into recursion with the caveat that a stack overflow may occur. However , not all recursions can be transformed directly into iteration. Often you will need some form of scratch space to hold the data that would otherwise be stored on the stack. As for which to choose: that depends on your language on and the convenience of writing a recursive solution. Strictly speaking, recursion and iteration are both equally powerful.

Any recursive solution can be implemented as an iterative solution with a stack. The inverse transformation can be trickier, but most trivial is just passing the state down through the call chain. In Java, there is one situation where a recursive solution is better than a naive iterative one, and one situation where they are basically equivalent. In most other cases, the iterative solution will be superior, since function call overhead is avoided. If the function uses a stack implicitly, then the recursive solution will typically be superior.

Consider a depth-first search:. In the recursive case, you will use the process stack, which will not create any garbage or allocate any memory. The recursive solution is vulnerable to a stack overflow, but will run faster otherwise. If the function uses tail recursion, then the two solutions will be equivalent because the JIT will transform the recursive one into the iterative one.

Tail recursion is when the last thing that a function does is invoke itself recursively, allowing the compiler to ignore any accumulated state. For example, traversing a list. In most other situations, an iterative solution will be superior. For example, if you wanted to do a breadth-first search, then you could use a Queue instead of a Stack in the iterative solution, and have it work instantly, while transforming it to a recursive solution requires that you pay for both the implicit stack in the call stack, and still pay for the queue.

The statement, "Recursion is always better than iteration" is false. There are cases when either one is preferable over the other. It's difficult to give you a decisive answer over which type of algorithm to use because it depends on the particular case.

For example, the common textbook recursion case of the Fibonacci sequence is incredibly inefficient using recursion, so it's better to use iteration in that case.

Conversely, traversing a tree can be implemented more efficiently using recursion. To answer your second question, yes, any iterative algorithm can be implemented using recursion and vice-versa.

If we remember the pass by value mechanism of java we can understand that the recursion consumes more memory as for each call you pass a copy of the object reference address or value of some primitive type. So as mach parameters you pass for each recursive call as mach memory you will consume for each call, on the other hand loops are light to use.

Improve Article. Like Article. Python3 program to find factorial of given number. Method to find the factorial of a given number. This code is contributed by mits. Output: Factorial of 5 using Recursion is: Factorial of 5 using Iteration is: Next Recursion.

Recommended Articles. Find maximum and minimum element in binary tree without using recursion or stack or queue. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Please use ide.



0コメント

  • 1000 / 1000