使用递归查找最大值

时间:2018-03-29 21:21:41

标签: java recursion

它让我脱离了异常。似乎没有认识到数组中的第一个元素。

public class MaximumRec {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] A = {90, 45,12,19,72,55,15,19};
        int x = maximumR(A,8);
        System.out.print(x);

    }

    static int maximumR(int[] A, int n)
    {
        int max;
        if (n == 1)
        {
            return A[n];
        }
        else
        {
             max = maximumR(A, n-1);
             if(max < A[n] )
             {
                 max = A[n];
             }
        }
        return max;
    }

}

2 个答案:

答案 0 :(得分:1)

这是因为您分配给n的8。然后你要求数组中的第8个元素,但是数组从0开始计数,所以A [8]不存在。最大值为A [7]。

答案 1 :(得分:0)

Java遵循C风格索引或基于零的编号,其中索引从0开始而不是1.另一个好的做法是动态分配数字而不是硬编码。

e.g。

free(token);
相关问题