Im learning arrays and Im trying to reverse the order in an array. This is the method I’ve got this far but it’s only working for the first half of the values in the array. What am I doing wrong?
public static void reverse(int[] anArray)
{
int[] a = anArray ;
for (int j = 0; j <= (a.length - 1); j++ )
{
anArray[j] = a[(anArray.length - j - 1)];
}
}
You need to make a temporary location in order to do the swap. This code write the end of the array to the front, but by the time you get to writing the end of the array, the first half of the values have already been lost.
Additionally, you are incrementing
jtwice. The last part of the for loop definition does the increment between each loop. You don’t need to do it manually inside the loop block.