Modify a given matrix by placing sorted boundary elements in clockwise manner | Function to print the elements of the matrix in row - wise manner ; Function to sort boundary elements of a matrix starting from the outermost to the innermost boundary and place them in a clockwise manner ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Stores the current boundary elements ; Push the first row ; Push the last column ; Push the last row ; Push the first column ; Sort the boundary elements ; Update the first row ; Update the last column ; Update the last row ; Update the first column ; Print the resultant matrix ; Given matrix
function printMatrix ( a ) { for ( let i = 0 ; i < a . length ; i ++ ) { for ( let j = 0 ; j < a [ i ] . length ; j ++ ) { document . write ( a [ i ] [ j ] + " " ) ; } document . write ( " " ) ; } } function sortBoundaryWise ( a ) { let i , k = 0 , l = 0 ; let m = a . length , n = a [ 0 ] . length ; let n_i , n_k = 0 , n_l = 0 , n_m = m , n_n = n ; while ( k < m && l < n ) { let boundary = [ ] ; for ( i = l ; i < n ; ++ i ) { boundary . push ( a [ k ] [ i ] ) ; } k ++ ; for ( i = k ; i < m ; ++ i ) { boundary . push ( a [ i ] [ n - 1 ] ) ; } n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) { boundary . push ( a [ m - 1 ] [ i ] ) ; } m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) { boundary . push ( a [ i ] [ l ] ) ; } l ++ ; } boundary . sort ( function ( a , b ) { return a - b ; } ) ; let ind = 0 ; for ( i = n_l ; i < n_n ; ++ i ) { a [ n_k ] [ i ] = boundary [ ind ] ; ind ++ ; } n_k += 1 ; for ( i = n_k ; i < n_m ; ++ i ) { a [ i ] [ n_n - 1 ] = boundary [ ind ] ; ind ++ ; } n_n -- ; if ( n_k < n_m ) { for ( i = n_n - 1 ; i >= n_l ; -- i ) { a [ n_m - 1 ] [ i ] = boundary [ ind ] ; ind ++ ; } n_m -- ; } if ( n_l < n_n ) { for ( i = n_m - 1 ; i >= n_k ; -- i ) { a [ i ] [ n_l ] = boundary [ ind ] ; ind ++ ; } n_l ++ ; } } printMatrix ( a ) ; } let matrix = [ ] ; let list1 = [ 9 , 7 , 4 , 5 ] ; let list2 = [ 1 , 6 , 2 , - 6 ] ; let list3 = [ 12 , 20 , 2 , 0 ] ; let list4 = [ - 5 , - 6 , 7 , - 2 ] ; matrix . push ( list1 ) ; matrix . push ( list2 ) ; matrix . push ( list3 ) ; matrix . push ( list4 ) ; sortBoundaryWise ( matrix ) ;