递归或循环 [英] Recursion or Looping

查看:75
本文介绍了递归或循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法可以计算一些统计信息:

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?

如果您有时间请解释您的答案:)

please if you have time explain your answer :)

推荐答案

常规递归

通常,递归会更昂贵,因为每次函数递归时都必须使用变量的副本来修改堆栈.

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.

从维护的角度来看,调试迭代代码比递归过程容易得多,因为与考虑特定的递归相比,它更容易理解任何特定迭代的状态.

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.

该过程会自行调用,但每次运行都与上一次运行的结果无关. 每次运行都是独立的,通常是最大的礼物,因此可能不需要递归.

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.

我认为,calculateAverage(hour + 1);应该移到该函数之外,因为对于阅读您的代码的人来说,这也更清楚.每个呼叫都是独立的.

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.

这篇关于递归或循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆