博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Iteration Vs Recursion Java
阅读量:4031 次
发布时间:2019-05-24

本文共 5833 字,大约阅读时间需要 19 分钟。

1. Recursion

Consider the factorial function: n!=n*(n-1)*(n-2)*...*1

There are many ways to compute factorials. One way is that n! is equal to n*(n-1)!. Therefore the program can be directly written as:

Program 1:

int factorial (int n) {
if (n == 1) {
return 1; } else {
return n*factorial(n-1); }}

In order to run this program, the computer needs to build up a chain of multiplications: factorial(n) → factorial(n-1) → factorial(n-2) → ... → factorial(1). Therefore, the computer has to keep track of the multiplications to be performed later on. This type of program, characterized by a chain of operations, is called recursion. Recursion can be further categorized into linear and treerecursion. When the amount of information needed to keep track of the chain of operations grows linearly with the input, the recursion is called linear recursion. The computation of n! is such a case, because the time required grows linearly with n. Another type of recursion, tree recursion, happens when the amount of information grows exponentially with the input. But we will leave it undiscussed here and go back shortly afterwards.

2. Iteration

A different perspective on computing factorials is by first multiplying 1 by 2, then multiplying the result by 3, then by 4, and so on until n. More formally, the program can use a counter that counts from 1 up to n and compute the product simultaneously until the counter exceeds n. Therefore the program can be written as:

Program 2:

int factorial (int n) {
int product = 1; for(int i=2; i

This program, by contrast to program 2, does not build a chain of multiplication. At each step, the computer only need to keep track of the current values of the product and i. This type of program is called iteration, whose state can be summarized by a fixed number of variables, a fixed rule that describes how the variables should be updated, and an end test that specifies conditions under which the process should terminate. Same as recursion, when the time required grows linearly with the input, we call the iteration linear recursion.

3. Recursion vs Iteration

Compared the two processes, we can find that they seem almost same, especially in term of mathematical function. They both require a number of steps proportional to n to compute n!. On the other hand, when we consider the running processes of the two programs, they evolve quite differently.

In the iterative case, the program variables provide a complete description of the state. If we stopped the computation in the middle, to resume it only need to supply the computer with all variables. However, in the recursive process, information is maintained by the computer, therefore "hidden" to the program. This makes it almost impossible to resume the program after stopping it.

4. Tree recursion

As described above, tree recursion happens when the amount of information grows exponentially with the input. For instance, consider the sequence of Fibonacci numbers defined as follows:

recursion-iteration-java

By the definition, Fibonacci numbers have the following sequence, where each number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...

A recursive program can be immediately written as:

Program 3:

int fib (int n) {
if (n == 0) {
return 0; } else if (n == 1) {
return 1; } else {
return fib(n-1) + fib(n-2); }}

Therefore, to compute fib(5), the program computes fib(4) and fib(3). To computer fib(4), it computes fib(3) and fib(2). Notice that the fib procedure calls itself twice at the last line. Two observations can be obtained from the definition and the program:

  1. The ith Fibonacci number Fib(i) is equal to phi(i)/rootsquare(5) rounded to the nearest integer, which indicates that Fibonacci numbers grow exponentially.
  2. This is a bad way to compute Fibonacci numbers because it does redundant computation. Computing the running time of this procedure is beyond the scope of this article, but one can easily find that in books of algorithms, which is O(phi(n)). Thus, the program takes an amount of time that grows exponentially with the input.

On the other hand, we can also write the program in an iterative way for computing the Fibonacci numbers. Program 4 is a linear iteration. The difference in time required by Program 3 and 4 is enormous, even for small inputs.

Program 4:

int fib (int n) {
int fib = 0; int a = 1; for(int i=0; i

However, one should not think tree-recursive programs are useless. When we consider programs that operate on hierarchically data structures rather than numbers, tree-recursion is a natural and powerful tool. It can help us understand and design programs. Compared with Program 3 and 4, we can easily tell Program 3 is more straightforward, even if less efficient. After that, we can most likely reformulate the program into an iterative way.

Reference:
1. 

width="728" height="90" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" id="aswift_0" name="aswift_0" style="margin: 0px; padding: 0px; left: 0px; position: absolute; top: 0px;">
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.programcreek.com%2F2012%2F10%2Fiteration-vs-recursion-in-java%2F&layout=button_count&show_faces=false&width=50&action=like&font=verdana&colorscheme=light&height=21" scrolling="no" frameborder="0" allowtransparency="true" style="margin: 0px; padding: 0px; border-style: none; overflow: hidden; width: 50px; height: 21px;">
Category >>    
If you want to post syntax highlighted code and let me or someone else review it, please put the code inside <pre><code> and </code></pre> tags. 

For example: 

 String foo = "bar";

转载地址:http://rnhbi.baihongyu.com/

你可能感兴趣的文章
Jetty 和 Tomcat 之争,到底孰强孰弱
查看>>
Tomcat 的类加载机制与 JVM 有何不同
查看>>
高并发之限流算法:计数器、漏桶、令牌桶
查看>>
Tomcat 之 server.xml 优化配置
查看>>
消息中间件:谈一谈 RocketMQ 的技术架构
查看>>
微服务统一认证,OAuth2 的认证流程
查看>>
Dubbo性能有多强,来看下官方的性能测试报告
查看>>
Kafka的常用使用场景:从初级到高级,你用到了几个
查看>>
阿里技术团队推荐:Dubbo 服务化最佳实践
查看>>
Nginx 限流常用模块:限制并发和IP访问频率
查看>>
OpenResty 高性能服务器,单机可达10K
查看>>
RocketMQ的十二个特性,你都知道吗「上」
查看>>
RocketMQ的十二个特性,你都知道吗「下」
查看>>
一文搞懂RocketMQ最常见的16个基本概念
查看>>
Intellij IDEA启动优化,让开发的感觉飞起来
查看>>
玩转Java高并发?请先说明下并发下的惊群效应
查看>>
轻松搭建Redis 5.0集群环境,只需十分钟
查看>>
Jmeter压测错误,Address already in use: connect
查看>>
高并发API网关,Spring Cloud Gateway 之限流操作
查看>>
OAuth2.0 微服务认证授权,四种常见的授权模式
查看>>