How Do I Reverse An Array Recursively

Hasnain Ali :

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.

sidgate :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144477&siteId=1