0

I am trying to reverse the order of a sub-array between the indices of start and end strictly using recursion. For example, if the subarray is 1,2,3,4 , it will become 4,3,2,1.

However, I am getting the following runtime error:

java.lang.ArrayIndexOutOfBoundsException: -1

at finalExam.reverse(finalExam.java:13)

at finalExam.reverse(finalExam.java:17)

I am not sure how to fix this problem.

Thanks.

 double[] reverse (double[] a, int start, int end) {
 if (start == end) {return a;}
 else {
 a[start] = a[end];
 a[end] = a[start];}


 return reverse (a, start+1, end-1);
}
5
  • 1
    You could do a check at the beginning of the method to see if the index you have reached is greater than the length of the array. Commented Apr 15, 2014 at 1:47
  • Classic tail recursion, meaning you shouldn't write it as recursion but as a simple loop. (A good compiler may save you from this mistake, or may not.) Commented Apr 15, 2014 at 1:58
  • "finalExam.java" so... we're helping you with a test? Is this permitted by your course? Commented Apr 15, 2014 at 1:58
  • Has your professor shown you programming with boxes or hand simulating your assignments? Your indices aren't your only problem, try doing this on paper step by step. Commented Apr 15, 2014 at 2:00
  • This was a question on a final exam which was completed a few hours ago on paper. The course is now over. Commented Apr 15, 2014 at 2:03

1 Answer 1

1

(Since you mention the exam is over). Here are the problems with your code:

  • Your check should be start >= end
  • Your code for swapping two numbers is incorrect.

Here is the correct solution:

public static double[] reverse (double[] a, int start, int end) {
    if (start >= end) {
        return a;
    }
    else {
        // this code will swap two elements
        double temp = a[start];
        a[start] = a[end];
        a[end] = temp;
    }
    return reverse (a, start+1, end-1);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.