[英]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.