33.8k views
3 votes
Write a method named reversecopy that takes an array of integers and returns a copy of the array with its elements in reverse order. The original array is not modified.

Example: reverseCopy(new int []{1,2,3} ) returns {3,2,1}

1 Answer

4 votes

Final answer:

To reverse an array and create a copy, iterate over the original array in reverse order and copy each element into a new array.

Step-by-step explanation:

To solve this problem, you can create a new array of the same length as the original array. Then, you can iterate over the original array from the last element to the first element, and copy each element into the new array in reverse order. Finally, return the new array.

Here's an example implementation in Java:

public static int[] reverseCopy(int[] arr) {
int len = arr.length;
int[] reversedArr = new int[len];

for (int i = len - 1; i >= 0; i--) {
reversedArr[len - 1 - i] = arr[i];
}
return reversedArr;
}

For example, if you call reverseCopy(new int[]{1, 2, 3}), it will return {3, 2, 1}.

User Northtree
by
7.7k points