Sorting rows of matrix in ascending order followed by columns in descending order | Javascript implementation to sort the rows of matrix in ascending order followed by sorting the columns in descending order ; function to sort each row of the matrix according to the order specified by ascending . ; 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 [ ] [ ] in descending order . ; again get transpose of mat [ ] [ ] ; function to print the matrix ; Driver code
let MAX_SIZE = 10 ; function sortByRow ( mat , n , ascending ) { for ( let i = 0 ; i < n ; i ++ ) { if ( ascending ) mat [ i ] . sort ( function ( a , b ) { return a - b ; } ) ; else mat [ i ] . sort ( function ( a , b ) { return b - a ; } ) ; } } function transpose ( mat , n ) { for ( let i = 0 ; i < n ; i ++ ) for ( let j = i + 1 ; j < n ; j ++ ) { let temp = mat [ i ] [ j ] ; mat [ i ] [ j ] = mat [ j ] [ i ] ; mat [ j ] [ i ] = temp ; } } function sortMatRowAndColWise ( mat , n ) { sortByRow ( mat , n , true ) ; transpose ( mat , n ) ; sortByRow ( mat , n , false ) ; transpose ( mat , n ) ; } function printMat ( mat , n ) { for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < n ; j ++ ) document . write ( mat [ i ] [ j ] + " " ) ; document . write ( " " ) ; } } let n = 3 ; let mat = [ [ 3 , 2 , 1 ] , [ 9 , 8 , 7 ] , [ 6 , 5 , 4 ] ] ; document . write ( " " ) ; printMat ( mat , n ) ; sortMatRowAndColWise ( mat , n ) ; document . write ( " " ) ; printMat ( mat , n ) ;