簡體   English   中英

Java求和遞歸方法

[英]Java summing recursive method

給我一個整數數組,並嘗試定義一個遞歸方法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);

您已誤讀一個字符。 返回線上的5應該是s

return A[s] + 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.
  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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM