Writing code to reverse the elements in an array. Both method1 and method2 perform the same operations, but are changing the values of the array in main, despite scope and no assignment.
import java.util.Arrays;
public class ReversingMatrix {
public static void main(String[] args) {
int values[] = {1, 2, 3, 4, 5, 6, 7};
method1(values, 0, values.length - 1);
// Values array is now : {7, 6 ... 1} --> why?
method2(values);
}
public static void method1(int[] arr, int lPos, int rPos) {
if(lPos >= rPos) System.out.println("1D Recursion Reverse: " + Arrays.toString(arr));
else {
int temp = arr[lPos];
arr[lPos] = arr[rPos];
arr[rPos] = temp;
method1(arr, lPos + 1, rPos - 1);
}
}
public static void method2(int[] arr) {
int temp;
for(int a = 0; a < arr.length / 2; a++) {
temp = arr[a];
arr[a] = arr[arr.length - (1+a)];
arr[arr.length - (1+a)] = temp;
}
System.out.println("1D For Loop Reverse: " + Arrays.toString(arr));
}
}
Why doesn't values array remain {1, 2, 3, 4, 5, 6, 7}
, so I can use it multiple times?