I am trying to reverse an array in 2 ways:
1) By creating a new array which was very easy:
public static int[] reverse(int[] array) {
int[] reverseArray = new int[array.length];
for(int i = 0; i < reverseArray.length; i++) {
reverseArray[i] = array[array.length - i - 1];
}
return reverseArray;
}
2) The second method I got my answer but I actually don’t understand it very well, it actually makes use of swapping, giving the value of the array to a temporary variable then changes it and returns it to the original variable:
public static int[] reverse2(int[] array)
{
for (int i=0; i < array.length / 2; i++)
{
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
return array;
}
Could someone explain to me the second code?
I don’t understand the division by 2?
What happens if the array size is even or odd?
The division by 2 is merely so you only go through the first half of the array. If you swap the first and last items, you don’t want to do it again when i reaches array.length. If the size is even, it will stop before the second half, if the size is odd, it will stop before the center position, which doesn’t need to be switched anyway. Hope that helps!