文章讲的是递归和迭代的区别。
这是在计算机科学中称为算法分析的主题下。
假设我编写了斐波那契函数,它看起来像这样:
//finds the nth fibonacci
int rec_fib(n) {
if(n == 1)
return 1;
else if (n == 2)
return 1;
else
return fib(n-1) + fib(n - 2)
}
如果你把它写在纸上(我推荐这个),你会看到这个看起来像金字塔的形状出现了。
它需要一个完整的电话来完成工作。
然而,还有另一种写斐波那契的方式(还有其他几种方式)
int fib(int n) //this one taken from scriptol.com, since it takes more thought to write it out.
{
int first = 0, second = 1;
int tmp;
while (n--)
{
tmp = first+second;
first = second;
second = tmp;
}
return first;
}
这个只需要与 n 成正比的时间长度,而不是你之前看到的二维生长的大金字塔形状。
通过算法分析,您可以准确地确定这两个函数的运行时间与 n 大小的增长速度。
此外,一些递归算法很快(或者可以被欺骗变得更快)。这取决于算法——这就是算法分析重要且有用的原因。
那有意义吗?