我得到了一个整数数组,并试图定义一个递归方法sum(int[] A,int s,int e)来计算数组A的总和,其中s和e是起始索引和结束索引。我想用给定的数组 int[] A= {3,5,8,9,10} 来测试它。
我对如何做到这一点感到困惑,但这是我到目前为止所拥有的(我什至对这里的代码有点困惑,因为我的朋友帮我写了它,一点解释会有很大帮助!
public static int sum(int[]A,int s,int e) {
if (s==e)
return A[e];
else
return A[5] + sum(A,s+1,e);
正如@KlasLindbäck的回答中所发布的那样,5 应该是 s。
public static int sum(int[]A,int s,int e) {
if (s==e)
return A[e];
else
return A[s] + sum(A,s+1,e);
要提供解释,请执行以下操作:
首先,调用此方法:
int theSum = sum(myArray, 0, myArray.length-1);
我将为您运行{3,5,8,9,10}数组。
sum(A, 0, 4):
return A[0] + sum(A, 1, 4) //3 + sum(A, 1, 4)
sum(A, 1, 4):
return A[1] + sum(A, 2, 4) //5 + sum(A, 2, 4)
sum(A, 2, 4):
return A[2] + sum(A, 3, 4) //8 + sum(A, 3, 4)
sum(A, 3, 4):
return A[3] + sum(A, 4, 4) //9 + sum(A, 4, 4)
sum(A, 4, 4):
return A[4] //10
Now, we know that sum(A, 4, 4) is 10, so therefore sum(A, 3, 4) is 9 + 10 = 19.
Now, we know that sum(A, 3, 4) is 19, so therefore sum(A, 2, 4) is 8 + 19 = 27.
Now, we know that sum(A, 2, 4) is 27, so therefore sum(A, 1, 4) is 5 + 27 = 32.
Now, we know that sum(A, 1, 4) is 32, so therefore sum(A, 0, 4) is 3 + 32 = 35.
你看错了一个字符。5
应该是回流线上的s
:
return A[s] + sum(A,s+1,e);
package com.TTC.Tryfon.AbdulRahman;
public class Doing {
public static void main(String[] args) {
int [] z={3,5,8,9,10};
System.out.println(sum(z,0));
}
public static int sum(int [] a,int index){
if(index<a.length){
return a[index]+sum(a,index+1);
}
return 0;
}
}
上述程序将产生以下结果:
35
为了理解程序,让我们执行这部分:
if(index<a.length){
return a[index]+sum(a,index+1);
}
索引从 0 开始,a.length=5:
if(0<5){
return a[0]+sum(a,0+1);
// this means return 3+sum(a,1);
}
if(1<5){
return a[1]+sum(a,1+1);
// this means return 5+sum(a,2);
}
if(2<5){
return a[2]+sum(a,2+1);
// this means return 8+sum(a,3);
}
if(3<5){
return a[3]+sum(a,3+1);
// this means return 9+sum(a,4);
}
if(4<5){
return a[4]+sum(a,4+1);
// this means return 10+sum(a,5);
}
if(5<5){
// 5 is not smaller than 5, so it will return 0;
}
return 0;
由于不再有函数调用,我们必须将返回的数字替换为函数调用:
10+0
9+10
8+18
5+27
3+32 =35
这是我第一次解释,希望好。
您还可以在递归调用中包含停止条件:
public static int sum(int[]A,int s,int e) {
return A[s] + (s == e) ? 0 : sum(A, s+1, e);
}