Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion vs loops

I'm facing a problem where both recursion and using a loop seem like natural solutions. Is there a convention or "preferred method" for cases like this? (Obviously it is not quite as simple as below)

Recursion

Item Search(string desired, Scope scope) {     foreach(Item item in scope.items)         if(item.name == desired)             return item;      return scope.Parent ? Search(desired, scope.Parent) : null; } 

Loop

Item Search(string desired, Scope scope) {     for(Scope cur = scope; cur != null; cur = cur.Parent)         foreach(Item item in cur.items)             if(item.name == desired)                 return item;      return null; } 
like image 939
zildjohn01 Avatar asked Mar 18 '09 22:03

zildjohn01


People also ask

Is recursion same as loops?

The main difference between recursion and loop is that recursion is a mechanism to call a function within the same function while loop is a control structure that helps to execute a set of instructions again and again until the given condition is true. Recursion and loop are two programming concepts.

Why do we use recursion instead of loops?

Recursion is made for solving problems that can be broken down into smaller, repetitive problems. It is especially good for working on things that have many possible branches and are too complex for an iterative approach . One good example of this would be searching through a file system.


2 Answers

I favor recursive solutions when:

  • The implementation of the recursion is much simpler than the iterative solution, usually because it exploits a structural aspect of the problem in a way that the iterative approach cannot

  • I can be reasonably assured that the depth of the recursion will not cause a stack overflow, assuming we're talking about a language that implements recursion this way

Condition 1 doesn't seem to be the case here. The iterative solution is about the same level of complexity, so I'd stick with the iterative route.

like image 181
John Feminella Avatar answered Oct 04 '22 03:10

John Feminella


If performance matters, then benchmark both and choose on a rational basis. If not, then choose based on complexity, with concern for possible stack overflow.

There is a guideline from the classic book The Elements of Programming Style (by Kernighan and Plauger) that algorithm should follow data structure. That is, recursive structures are often processed more clearly with recursive algorithms.

like image 20
RBerteig Avatar answered Oct 04 '22 05:10

RBerteig