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