Cody Cody - 2 months ago 5
Java Question

Java array order reversing

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)];
}
}

Answer

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.

public static void reverse(int[] a)
{
    int l = a.length;
    for (int j = 0; j < l / 2; j++)
    {
        int temp = a[j]
        a[j] = a[l - j - 1];
        a[l - j - 1] = temp;
    }
}

Additionally, you are incrementing j twice. 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.

Comments