qad
qad

Reputation: 39

Finding maximum using recursion

It gives me out of bound exception. And it seems not to recognize the first element in the array.

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;
    }

}

Upvotes: 1

Views: 57

Answers (2)

Jigar Patel
Jigar Patel

Reputation: 1

Java follows C-style indexing or Zero-based numbering in which index starts from 0 instead of 1. Also a good practice would be to dynamically assign the number instead of hard coding it.

e.g.

int x = maximumR(A, A.length - 1);

Upvotes: 0

DarkAngel
DarkAngel

Reputation: 237

It's because of the 8 you assign to n. And then you ask for the 8th element in the array, but the array starts counting at 0 so the A[8] doesn't exists. The max is A[7].

Upvotes: 1

Related Questions