Sort the matrix row | Java implementation to sort the matrix row - wise and column - wise ; function to sort each row of the matrix ; sorting row number ' i ' ; function to find transpose of the matrix ; swapping element at index ( i , j ) by element at index ( j , i ) ; function to sort the matrix row - wise and column - wise ; sort rows of mat [ ] [ ] ; get transpose of mat [ ] [ ] ; again sort rows of mat [ ] [ ] ; again get transpose of mat [ ] [ ] ; function to print the matrix ; Driver code
import java . util . Arrays ; class GFG { static final int MAX_SIZE = 10 ; static void sortByRow ( int mat [ ] [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) Arrays . sort ( mat [ i ] ) ; } static void transpose ( int mat [ ] [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) { int temp = mat [ i ] [ j ] ; mat [ i ] [ j ] = mat [ j ] [ i ] ; mat [ j ] [ i ] = temp ; } } static void sortMatRowAndColWise ( int mat [ ] [ ] , int n ) { sortByRow ( mat , n ) ; transpose ( mat , n ) ; sortByRow ( mat , n ) ; transpose ( mat , n ) ; } static void printMat ( int mat [ ] [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 4 , 1 , 3 } , { 9 , 6 , 8 } , { 5 , 2 , 7 } } ; int n = 3 ; System . out . print ( "Original Matrix:NEW_LINE"); printMat ( mat , n ) ; sortMatRowAndColWise ( mat , n ) ; System . out . print ( " Matrix After Sorting : "); printMat ( mat , n ) ; } }