Search code examples
javaarrays2dreversereversing

How to reverse a 2D array in java?


I am trying to reverse all of the content in a 2D array. The last value should be the first, and the first value should be the last.

For example, an input of

[1,2,3],
[4,5,6],
[7,8,9] 

would return:

[9,8,7]
[6,5,4]
[3,2,1]

This is some code I have so far, but it is returning this:

9 8 3 
6 5 4 
7 2 1 
int[][] reverse = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for(int i = 0; i <= (reverse.length / 2); i++) {
    for(int j = 0; j < (reverse[0].length / 2) + 1; j++) {
        System.out.println(i + " " + j);
        System.out.println((reverse.length-1-i) + " " + (reverse[0].length -1 -j));
        int temp = reverse[reverse.length-1-i][reverse[0].length -1 -j];
        reverse[reverse.length-1-i][reverse[0].length - 1 - j] = reverse[i][j];
        reverse[i][j] = temp;
     }
}
for(int i = 0; i < reverse.length; i++) {
  for(int j = 0; j < reverse[0].length; j++) {
       System.out.print(reverse[i][j]+" ");
  }
  System.out.println("");
}

How can fix this so that the 3 and the 7 are switched?


Solution

  • Your inner loop needs to iterate to the end of each row, rather than to the middle, and you need to handle the middle row of arrays with an odd number of rows separately:

    static void reverse(int[][] arr)
    {
        int m = arr.length;
        int n = arr[0].length;
    
        for(int i=0; i<m/2; i++)
            for(int j=0; j<n; j++)
                swap(arr[i], j, arr[m-1-i], n-1-j);
        
        if(m % 2 == 1) 
        {
            int[] mid = arr[m/2];
            for(int j=0; j<n/2; j++)
                swap(mid, j, mid, n-1-j);
        }
    }
     
    
    
    static void swap(int[] a, int i, int[] b, int j)
    {
        int tmp = a[i];
        a[i] = b[j];
        b[j] = tmp;
    }
    

    Test:

    int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    reverse(arr);       
    for(int[] row : arr) System.out.println(Arrays.toString(row));
    

    Output:

    [9, 8, 7]
    [6, 5, 4]
    [3, 2, 1]