Optimized In Place Transpose of Square Matrix
This program performs in place transpose of a square matrix without using extra space.
Problem Statement
Write a Java program to transpose a 3x3 matrix in place.
Source Code
| 1 | public class InplaceTranspose { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq In Place Transpose"); |
| 4 | int[][] A = {{1,2,3},{4,5,6},{7,8,9}}; |
| 5 | for(int i=0;i<3;i++){ |
| 6 | for(int j=i+1;j<3;j++){ |
| 7 | int temp=A[i][j]; |
| 8 | A[i][j]=A[j][i]; |
| 9 | A[j][i]=temp; |
| 10 | } |
| 11 | } |
| 12 | for(int i=0;i<3;i++){ |
| 13 | for(int j=0;j<3;j++){ |
| 14 | System.out.print(A[i][j]+" "); |
| 15 | } |
| 16 | System.out.println(); |
| 17 | } |
| 18 | } |
| 19 | } |
Program Output
Eduinq In Place Transpose 1 4 7 2 5 8 3 6 9
Explanation
The transpose swaps elements across the main diagonal, and only the upper triangle (j starting from i+1) is processed to avoid swapping twice, so no extra matrix is required, demonstrating a memory-optimized in-place transpose.