Question:
Write a Java method named reverseArray
that takes an array of integers as a parameter and returns a new array with the elements in reverse order. The original array should remain unchanged. You may assume that the input array contains at least one element.
Use the following method header:
public static int[] reverseArray(int[] arr)
Example usage:
int[] arr = {1, 2, 3, 4, 5};
int[] reversedArr = reverseArray(arr);
System.out.println(Arrays.toString(reversedArr)); // [5, 4, 3, 2, 1]
Write the implementation of the reverseArray
method and provide a step-by-step explanation of your solution.
Answer:
public static int[] reverseArray(int[] arr) {
int[] reversedArr = new int[arr.length]; // create a new array of the same size
for (int i = 0; i < arr.length; i++) {
reversedArr[i] = arr[arr.length - 1 - i];
}
return reversedArr;
}
Explanation:
The method reverseArray
takes an array of integers as a parameter and returns a new array with the elements in reverse order.
We create a new array reversedArr
with the same length as the input array arr
. This new array will store the reversed elements.
We use a for
loop to iterate through the input array arr
.
Inside the loop, we assign the elements from the input array arr
to the corresponding positions in the new array reversedArr
in reverse order. We use the expression arr.length - 1 - i
to access the elements in reverse order. The element at index arr.length - 1
(which is the last element in the array) becomes the first element in the reversed array, the element at index arr.length - 2
becomes the second element, and so on.
Finally, we return the reversed array reversedArr
.
By using this implementation, we can reverse any given array of integers and return the reversed array without modifying the original array.