Java, recursively reverse an array

2020-03-01 08:34发布

I haven't found anything with the specific needs of my function to do this, yes, it is for homework.

So I have:

public void reverseArray(int[] x) {

}

Precondition: x.length > 0

The fact that I can't have the function return anything, and the only argument is an array is leaving me stumped.

I've tried using loops along with the recursion, but everything I've tried seems to end up with infinite instances of the function being made.

I've gotten an idea/suggestion to use another function along with this one, but, how to use the original recursively is beyond me at the moment.

Any help is appreciated.

13条回答
再贱就再见
2楼-- · 2020-03-01 09:20

Try something as below:

public void reverseArray(int[] x) {
    if(x.length ==2){
      //if two elements, swap them
      int first = x[0];
      x[0] = x[1];
      x[1] = first;
    }else if(x.length > 2){
      //swap first and last
      int first = x[0];
      x[0]= x[x.length-1];
      x[x.length-1] = first;
      //create a copy of middle elements
      int [] copy = new int[x.length-2];
      System.arraycopy( x, 1, copy, 0, x.length-2);
      //recursive call for middle elements
      reverseArray(copy);
      //place the reversed elements back in the original array
      System.arraycopy( copy, 0, x, 1, copy.length);
    }
}
查看更多
登录 后发表回答