Hasnain Ali
Hasnain Ali

Reputation: 462

How Do I Reverse An Array Recursively

I am trying to write a recursive method takes in an array of integers and simply returns that array backwards. Here is what I have thus far.

    private static int[] reverseArray(int arr[]) {
    int arrDup[] = arr.clone();
    int x = 0, y = arrDup.length - 1;

    if (arrDup[0] == arr[arr.length - 1]) {
        return arrDup;
    }
    else {
        // System.out.println(Arrays.toString(arrDup));
        arrDup[y--] = arr[x++];
        return reverseArray(arrDup);
    }
}

public static void main(String[] args) {
    int arrPass[] = {1, 2, 3, 4, 5};
    System.out.println(Arrays.toString(reverseArray(arrPass)));
}

How can I go about fixing this method so it can reverse it properly? When I run it, I only [1, 2, 3, 4, 1]. Assume that no elements in the array are repeated. I understand recursion, just trying to implement it here.

Upvotes: 3

Views: 1330

Answers (2)

Koushik Jay
Koushik Jay

Reputation: 21

Start from the array length -1 and decrease by 1 till the half of the array. You can get the starting position by simply using mod(%) . Use Array length -1 for index when initial calling.

 public int[] reverseIt(int index , int [] main_Arr){
    if(index==(main_Arr.length)/2){
      return main_Arr;
    }

    int a =main_Arr[(main_Arr.length-1)%index];
    int b =main_Arr[index];
    main_Arr[(main_Arr.length-1)%index]=b;
    main_Arr[index]=a;
    reverseIt(index-1, main_Arr);
    return main_Arr;
}

Upvotes: 0

sidgate
sidgate

Reputation: 15244

Following should be the recursive solution

  • Swap first and last number
  • Reverse rest of the array

Swapping would require a temporary variable.

static void reverseArray(int[] arr, int start, int end) {
    if (start >= end)
        return;
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    reverseArray(arr, start + 1, end - 1);
}

public static void main(String[] args) {
    reverseArray(new int[]{1, 2, 3, 4, 5}, 0, 4);
}

Upvotes: 4

Related Questions