In addition to previous answers, which address valid points, I'd like to point out that your code is not scalable. If a matrix always has exactly 16 elements, time and space complexity are not really an issue, as they describe how the algorithm behaves at different scales.
You should figure out the row and column count of the matrix beforehand, and use these values when creating transposedArray
and in your for
loops.
As for time and space complexity, they both can be improved, as noted by Sharon Ben Asher in his answer. To go in further details, your algorithm performs n*m
operations, or n²
operations if m = n
. Iterating on the upper half triangle reduces the number of operations to n * (n-1) / 2
, which is a sizeable improvement by a factor 2. However, this would fail on a non-square matrix see the example below:
input | expected | iteration on
| output | upper triangle
-------------------------------------------
a b c d | a e i | a e i d
e f g h | b f j | b f j h
i j k l | c g k | c g k l
| d h l |
As you state that you are currently learning big O notation, note that the time complexity is still O(n²)
, as it is still the dominant term in the number of operations performed. The improvement is far from negligible, but it isn't represented in big O notation.
As of space complexity, swapping elements in place doesn't require allocating another n*m
array to store the results of the operation. This means an improvement in terms of space complexity from O(n²)
to O(1)
. This is great, especially with larger inputs. However, this also fails for non-square inputs, and means the input is mutated. If you happen to need the input in its original state, you'd have to transpose the matrix again.
Depending on the exact behavior you need, iterating on the full matrix or the upper triangle, and transposing in place or returning a transposed array can both be justified.
Finally, for integration purposes, your class could use some refactoring, most importantly to allow processing a matrix of any size.