简体   繁体   English

迭代与递归的最大区别是什么?

[英]What is the Big O difference for iterative vs recursive?

What is the Big O difference for iterative vs recursive? 迭代与递归的最大区别是什么? And why are the run times so different. 以及为什么运行时间如此不同。 I would assume O(n) as it has one loop for the iterative. 我会假设O(n)为迭代的一个循环。

Here is a medium article with a nice graph. 这是一篇带有精美图表的中篇文章

function factorial (n) {
  if( n === 0 || n === 1 ) {
    return 1;
  }
  let prev = 1;
  let ret;
  while(n >= 2) {
    ret = prev * n;
    prev = ret;
    n--;
  }
  return ret;
}

function factorialR (n) {
  if( n === 0 || n === 1 ) {
    return 1;
  } else {
    return n * factorialR(n - 1);
  }
}

The recursive version seems to take significantly longer. 递归版本似乎需要更长的时间。 See SO Q/A here. 请参阅此处的SO Q / A。 .

Yes, those functions both have O(n) computational complexity, where n is the number passed to the initial function call. 是的,这些函数都具有O(n)计算复杂度,其中n是传递给初始函数调用的数字。

The first function executes the ( O(1) complexity) statements in the while loop for every value between a larger n and 2, for an overall complexity of O(n) . 对于O(n)的整体复杂度,第一个函数在while循环中为较大的n和2之间的每个值执行( O(1)复杂度)语句。

The second function recursively calls itself n times, without any loops, for (again) an overall complexity of O(n) . 第二个函数以O(n)的整体复杂度递归调用自身n次,没有任何循环。

If you wanted to reduce the computational complexity for multiple calls of the functions, I'd create a lookup table to save the values calculated from previous calls, resulting in m calls of the function running in O(n) (where n is the highest number ever passed), rather than m calls running in O(n * m) (or O(n^2) ) time. 如果您想降低函数多次调用的计算复杂度,我将创建一个查找表来保存从先前调用中计算出的值,从而导致该函数的m调用在O(n)运行(其中n为最高而不是在O(n * m) (或O(n^2) )时间内运行的m调用。

If 如果

The recursive version seems to take significantly longer. 递归版本似乎需要更长的时间。

this is not due to computational complexity, but due to how the compiler works with the different approaches. 不是由于计算复杂性,而是由于编译器如何使用不同的方法。 Function calls generally have more of an overhead than a simple while loop (though, this sort of optimization is almost never something to worry about in real life - code readability and maintainability is more important most of the time). 函数调用通常比简单的while循环具有更多的开销(尽管,这种优化在现实生活中几乎永远不用担心-在大多数情况下,代码的可读性和可维护性更为重要)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM