TimelordViktorious
TimelordViktorious

Reputation: 336

Array swap - 2d array

I'm working on swapping indices in a two-dimensional array. I seem to be on the right track, but it's not swapping the array in the way I want.

The first row's index j needs to be swapped with row 2's index j:

for (int j = 0; j < array.length ; j++){  
     int temp = array[row1][j]
     array[row1][j]=array[j][row1]
     array[j][row1] = temp ;
}

Any ideas on how to best approach this would be appreciated.

Upvotes: 4

Views: 23341

Answers (1)

mreithub
mreithub

Reputation: 1222

As the two-dimensional array in java is actually a array of references to other arrays, you can simply swap the references as shown below:

public static void swapRows(int array[][], int rowA, int rowB) {
   int tmpRow[] = array[rowA];
   array[rowA] = array[rowB];
   array[rowB] = tmpRow;
}

/edit: edited the answer as I previously misinterpreted it**

Upvotes: 4

Related Questions