Knowee
Questions
Features
Study Tools

Write a java method to reverse the elements of an array using recursion. Your method should take an array as an input parameter and return reverse the array

Question

Write a java method to reverse the elements of an array using recursion.

Your method should take an array as an input parameter and return reverse the array.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Java method that reverses an array using recursion:

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

    static void printArray(int arr[], int size) {
        for (int i=0; i < size; i++)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

    public static void main (String[] args) {
        int arr[] = {1, 2, 3, 4, 5, 6};
        printArray(arr, 6);
        reverseArray(arr, 0, 5);
        System.out.println("Reversed array is ");
        printArray(arr, 6);
    }
}

Here's how it works:

  1. The reverseArray method takes an array and two indices (start and end) as input. The start index is initially 0 (the first element) and the end index is the last element of the array.

  2. If start is greater than or equal to end, it means we've traversed half of the array and swapped all the necessary elements, so we return from the method.

  3. If start is less than end, we swap the elements at these indices.

  4. We then call reverseArray again, but this time with start+1 and end-1. This means we're moving towards the middle of the array from both ends.

  5. This process continues until start is no longer less than end, at which point all elements have been swapped and the array is reversed.

  6. The printArray method is used to print the array before and after reversing.

This problem has been solved

Similar Questions

Which of the following methods can be used to reverse the elements of an array in Python?Optionsrevert()reverse()backward()inverse()

Write a Java program to remove the duplicate elements of a given array and return the new length of the array.

Which among the following methods is used to reverse the sequence of characters in a StringBuilder object?a)backwards()b)invert()c)reverse()d)flip()

Write a Java program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s

Write a Java program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s.

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.