Search code examples
javaarraysmethodsreverse

Java reverse array method


I'm trying to create a method that takes in an array and then returns that array in reverse. The code I wrote returns the array in reverse, but, the first two values are now 0. Anyone know what I did wrong?

public static int[] reverse(int[] x)
{     
    int []d = new int[x.length];

    for (int i = 0; i < x.length/2; i++)  // for loop, that checks each array slot
    {
        d[i] = x[i];
        x[i] = x[x.length-1-i];  // creates a new array that is in reverse order of the original
        x[x.length-1-i] = d[i];
    }
    return d;      // returns the new reversed array  
}

Solution

  • You are assigning values from an uninitialized array d to x - that's where the zeroes (default value for an int in Java) are coming from.

    IIUC, you're mixing two reversing strategies.

    If you're creating a new array, you needn't run over half of the original array, but over all of it:

    public static int[] reverse(int[] x) {
    
        int[] d = new int[x.length];
    
    
        for (int i = 0; i < x.length; i++) {
            d[i] = x[x.length - 1 -i];
        }
        return d;
    }
    

    Alternatively, if you want to reverse the array in place, you don't need a temp array, only a single variable (at most - there are also ways to switch two ints without an additional variable, but that's a different question):

    public static int[] reverseInPlace(int[] x) {
        int tmp;    
    
        for (int i = 0; i < x.length / 2; i++) {
            tmp = x[i];
            x[i] = x[x.length - 1 - i];
            x[x.length - 1 - i] = tmp;
        }
        return x; // for completeness, not really necessary.
    }