0

I have trouble understanding why an ArrayOutOfBounds occurs here. I'm not sure whether my recursion is correct but when I manually wrote it down on a piece of paper and went through the code step by step, I was able to reverse the entire array from X to Y. Could someone explain the error?

static int i = 0;

// Array X will copy the leftmost n elements into Array Y
static void reverseArray(int[] X, int n, int[] Y) {
    if (n > 0) {
        Y[n] = X[i];
        i++;
        reverseArray(X, n-1, Y);
    }
}

public static void main(String[] args) {
   int[] A = {-1, 2, 6, 12, 9, 2, -5, -2, 8, 5, 7};
   int[] B = new int[A.length];

   reverseArray(A, A.length, B);
   for(int x: B) System.out.print(x+" ");
   System.out.println();
}
  • 1
    You're using the array's length as the first index. That will give you out of bounds because array indices start at 0. So an array `a` with length 3 will have `a[0] a[1] a[2]` as valid indices. `a[3]` will give an out of bounds exception. It should be `reverseArray(A, A.length-1, B);` – Jayce444 Jul 06 '17 at 23:59
  • You can try Y[n - 1] = X[i]; You need to learn more basic knowledge about java. – Ke Li Jul 07 '17 at 00:00
  • Invoke with `reverseArray(A, A.length -1, B);` and compare n with >= 0 – Erwin Bolwidt Jul 07 '17 at 00:02
  • @ErwinBolwidt thanks for the reply, just tried with >= 0 but it still doesn't work. Is it necessary to change it to (A, A.length-1, B) when I already invoke reverseArray(X, n-1, Y) in the reverseArray method, which will subtract 1 for me? – Andrew Kwang Jul 07 '17 at 00:10
  • Yes it is necessary to change that. Array indices go from 0 to length - 1, not from 1 to length like your code was assuming. – Erwin Bolwidt Jul 07 '17 at 01:34

0 Answers0