4

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.

3
  • 6
    Please tell us what is "the way you want. Are you trying to transpose a square matrix? Commented Nov 8, 2012 at 0:22
  • do you want to get from [[0,1,2,3,4],[5,6,7,8,9]] to [[5,6,7,8,9],[0,1,2,3,4]]? Commented Nov 8, 2012 at 1:23
  • Yes. However, do keep in mind I have 4 rows. They aren't swappable in a specific order. I can swap row 1 with row 3 if I want, or row 2 with row -1, etc. Commented Nov 8, 2012 at 1:30

1 Answer 1

4

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**

Sign up to request clarification or add additional context in comments.

3 Comments

hmmm, I guess one could even start at int col=row+1 as e.g. array[10][10] doesn't need swapping with its opposite
Nope. I'm still not getting this right. I have to loop through indices j, and swap those indices from the first row to the 2nd row.
@MH1993 Edited the answer. Is that what you want?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.