Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion or Looping [duplicate]

I have this method that calculates some statistics:

public void calculateAverage(int hour){

    if (hour != 20) {
        int data =0; 
        int times = 0;
        for (CallQueue cq : queues) {
            data += cq.getCallsByTime().get(hour);
            times++;
        }       
        averageData.add((double)data/times);
        calculateAverage(hour + 1);
    }
    
}

Now I am very proud that I have created a recursive method but I know that this could have been solved with a loop.

My question is: is it better to solve these kind of problems recursive or with a loop?

like image 943
Marc Rasmussen Avatar asked Nov 12 '12 15:11

Marc Rasmussen


2 Answers

Recursion in general

In general, a recursion would be more expensive, because the stack has to be modified with copies of variables for each time the function recurses.

A set of addresses & states need to be saved, so that the recursive procedure can return to the right state after that particular run.

Iteration would be better if possible. Recursion, when iteration just won't cut it, or will result in a lot more complicated code.


Code Maintenance

From a maintenance perspective, debugging iterative code is a lot easier than recursive procedures as it is relatively easier to understand what the state is at any particular iteration, as compared to thinking about a particular recursion.


Your code

The procedure calls itself, but each run has nothing to do with the results of the previous run. Each run being independent, is usually the biggest give-away, that recursion there might not be necessary.

In my opinion, calculateAverage(hour + 1); should be moved outside the function, as it would also be clearer to someone reading your code. that each call is independent.

like image 57
Anirudh Ramanathan Avatar answered Sep 28 '22 05:09

Anirudh Ramanathan


In Java, C, and Python, recursion is fairly expensive compared to iteration (in general) because it requires the allocation of a new stack frame. In some C compilers, one can use a compiler flag to eliminate this overhead, which transforms certain types of recursion (actually, certain types of tail calls) into jumps instead of function calls. (source)

like image 22
dreamcrash Avatar answered Sep 28 '22 06:09

dreamcrash