According to this piece of code I must get a reverse array but I’m still getting the non-reversed.
public class Reversing_array {
public static void reverse_arr(int arr[]) {
int n = arr.length - 1;
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
arr[i] = arr[n - i];
arr[n - i] = temp;
}
}
public static void main(String[] args) {
int arr[] = { 10, 20, 30, 40, 50 };
reverse_arr(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
I performed a dry run of it, but still didn’t reached to the mistake.
>Solution :
If you have an array of four elements, and run swaps four times:
1 2 3 4 // initial state
4 2 3 1 // first swap
4 3 2 1 // second swap <- this is what we want
4 2 3 1 // third swap <- but we kept going...
1 2 3 4 // fourth swap <- and going...
You want to swap arr.length / 2 times to avoid re-swapping back into the original order. If the length of the array is odd, this will avoid swapping the middle element, but that’s okay.