Recursion and Iteration

前端 未结 7 550
故里飘歌
故里飘歌 2020-12-18 08:43

What is the difference? Are these the same? If not, can someone please give me an example?

MW: Iteration - 1 : the action or a process of iterating or repeating: as

相关标签:
7条回答
  • 2020-12-18 09:27

    We can distinguish (as is done in SICP) recursive and iterative procedures from recursive and iterative processes. The former are as your definition describes, where recursion is basically the same as mathematical recursion: a recursive procedure is defined in terms of itself. An iterative procedure repeats a block of code with a loop statement. A recursive process, however, is one that takes non-constant (e.g. O(n) or O(lg(n)) space) to execute, while an iterative process takes O(1) (constant) space.

    For mathematical examples, the Fibonacci numbers are defined recursively:

    Fibonacci function

    Sigma notation is analogous to iteration:

    harmonic number

    as is Pi notation. Similar to how some (mathematical) recursive formulae can be rewritten as iterative ones, some (but not all) recursive processes have iterative equivalents. All recursive procedures can be transformed into iterative ones by keeping track of partial results in your own data structure, rather than using the function call stack.

    0 讨论(0)
提交回复
热议问题