Your question doesn't really make too much sense without specifying considerably more of the context: the algorithms are assuming a linear representation of the data (which, since languages such as C[++] essentially directly access memory, makes sense in those contexts). Note that for this kind of representation, you need to represent the number of rows and columns externally to the data. So the data representation for a 3x4 matrix could equally well be used for a 4x3 (or 2x6, etc) matrix, you would just have different values for numberCols
and numberRows
(in pseudocode). So the transposition algorithms here use the same memory allocation, but re-order the elements and re-interpret the number of rows and columns.
If you represent a (integer) matrix in Java as int[][]
, then you can't use the same algorithm, or indeed any in-place transposition, because the number of rows and columns are fixed for that particular representation: arrays in Java are not resizable. The algorithm doesn't apply because the data representation is not linear in the same way.
But if you chose to represent your matrix using a single-dimension array:
public class IntMatrix {
private final int numColumns ;
private final int numRows ;
private final int[] data ;
public IntMatrix(int numColumns, int numRows, int... data) {
if (data.length != numColumns*numRows) {
throw new IllegalArgumentException("...");
}
this.numColumns = numColumns ;
this.numRows = numRows ;
this.data = new data[numColumns * numRows] ;
System.arrayCopy(data, 0, this.data, 0, this.data.length);
}
public int getElement(int row, int column) {
return data[column*numRows+row];
}
public int getNumRows() {
return numRows ;
}
public int getNumColumns() {
return numColumns ;
}
}
then you could certainly implement an in-place transpose with exactly the same algorithms.
However, you almost certainly wouldn't: you'd do the following:
public class IntMatrix {
// code as before...
public IntMatrix transpose() {
return new Transpose(this);
}
private static class Transpose extends IntMatrix {
private IntMatrix original ;
Transpose(IntMatrix original) {
this.original = original ;
}
@Override
public int getElement(int row, int column) {
return original.getElement(column, row) ;
}
@Override
public IntMatrix transpose() {
return original ;
}
@Override
public int getNumRows() {
return original.getNumColumns();
}
@Override
public int getNumColumns() {
return original.getNumRows();
}
}
}
which (for this immutable representation) creates a transpose with O(1) operations and O(1) additional memory. You can create mutable representations similarly, with a little more work, and possibly higher cost depending exactly on what exact behavior you want (transpose view of the original mutable matrix, etc).