![](/img/trans.png)
[英]Why does processing goes slower on implementing try catch block in java?
[英]Why does the recursion goes to else block instead of if?
class myclass {
static int fun(int a[],int n){
int x;
if(n == 1){
return a[0];
}
else{
x = fun(a, n-1);
if(x > a[n-1])
return x;
else
return a[n-1];
}
}
public static void main(String[] args){
int arr[] = {12, 10, 30, 50, 100};
System.out.println(fun(arr, 5));}
}
为什么 output 是 100 而不是 12。我不明白为什么当 n 的值为 1 时最后一次递归调用,它会阻塞而不是 if。
这是因为您正在寻找数组中的最大值。 将if(x > a[n-1])
更改为if(x < a[n-1])
将使您的程序为给定的输入返回 10。
这是因为您在最后返回到相同 function 的先前实例,因此您的方法调用和返回看起来像这样(每个级别缩进是一个 function 调用及其返回)。 如果您知道如何使用调试器,请单步执行您的代码并在 go 中查看并绘制此图,这将帮助您能够在脑海中可视化递归调用和每次返回的值。
fun(a[],5)
| fun(a[],4)
| | fun(a[],3)
| | | fun(a[],2)
| | | | fun(a[],1)
| | | | return 12
| | | return 12
| | return 30
| return 50
return 100
这里详细说明为什么结果是100 。
public class myclass {
static int fun(int a[],int n)
{
int x;
if(n == 1)
{
return a[0]; // Step (2) --> return x = 12, now again n = 5 then continue on line
}
else
{
x = fun(a, n-1); // Step (1) --> this line is same as x = fun(a, 1)
if(x > a[n-1]) // Step (3) --> at this point n = 5 again and x = 12 while a[4] = 100 which is not less than x, statement 12 > 100 is false, move on to else block
return x;
else
return a[n-1]; // Step (4) --> return a[4] which is 100 as see above
}
}
public static void main(String[] args)
{
int arr[] = {12, 10, 30, 50, 100};
System.out.println(fun(arr, arr.length));}
}
希望您能理解递归示例中缺少的内容!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.