Java, recursively reverse an array

后端 未结 13 1100
悲&欢浪女
悲&欢浪女 2020-12-17 16:44

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) {
         


        
13条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 17:23

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

提交回复
热议问题