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.
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:
-
The
reverseArray
method takes an array and two indices (start
andend
) as input. Thestart
index is initially 0 (the first element) and theend
index is the last element of the array. -
If
start
is greater than or equal toend
, it means we've traversed half of the array and swapped all the necessary elements, so we return from the method. -
If
start
is less thanend
, we swap the elements at these indices. -
We then call
reverseArray
again, but this time withstart+1
andend-1
. This means we're moving towards the middle of the array from both ends. -
This process continues until
start
is no longer less thanend
, at which point all elements have been swapped and the array is reversed. -
The
printArray
method is used to print the array before and after reversing.
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.
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.