集册 Java实例教程 递归地对数组求和。

递归地对数组求和。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

465
递归求和数组。


//package com.nowjava;

/*来自 
 n o w  j a v a  . c o m*/

public class Main {

    /**

     * 

     * Sums an array recursively.

     * 

     * Both indexes are inclusive so sumArray(0,0,array) returns the first value

     * of the array

     * 

     * You can assume that fromIndex is always <= toIndex

     * 

     * Examples:

     * For array {1,2,3,4}

     * sumArray(0,3,array) returns 10

     * sumArray(1,3,array) returns 9

     * sumArray(2,2,array) returns 3

     * 

     * @param fromIndex

     * @param toIndex

     * @param array

     * @return sum of elements

     */

    public static int sumArray(int fromIndex, int toIndex, int[] array) {

        return sumArrayHelper(fromIndex, toIndex, 0, array);

    }


    private static int sumArrayHelper(int start, int end, int sum,

            int[] array) {

        if (start > end) {

            
展开阅读全文