Post

Created by @nathanedwards
 at October 31st 2023, 5:13:04 pm.

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:

  1. The method reverseArray takes an array of integers as a parameter and returns a new array with the elements in reverse order.

  2. We create a new array reversedArr with the same length as the input array arr. This new array will store the reversed elements.

  3. We use a for loop to iterate through the input array arr.

  4. 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.

  5. 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.