text: Sort Matrix in alternating ascending and descending order rowwise | Javascript implementation to print row of matrix in ascending or descending order alternatively ; Iterate matrix rowwise ; Sort even rows in ascending order ; compare adjacent elements ; swap adjacent element ; Sort even rows in descending order ; compare adjacent elements ; swap adjacent element ; Printing the final Output ; Driver code
code: let N = 4 ; function func ( a ) { for ( let i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { for ( let j = 0 ; j < N ; j ++ ) { for ( let k = j + 1 ; k < N ; ++ k ) { if ( a [ i ] [ j ] > a [ i ] [ k ] ) { let temp = a [ i ] [ j ] ; a [ i ] [ j ] = a [ i ] [ k ] ; a [ i ] [ k ] = temp ; } } } } else { for ( let j = 0 ; j < N ; j ++ ) { for ( let k = j + 1 ; k < N ; ++ k ) { if ( a [ i ] [ j ] < a [ i ] [ k ] ) { let temp = a [ i ] [ j ] ; a [ i ] [ j ] = a [ i ] [ k ] ; a [ i ] [ k ] = temp ; } } } } } for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < N ; j ++ ) { document . write ( " " + a [ i ] [ j ] ) ; } document . write ( " " ) ; } } let a = [ [ 5 , 7 , 3 , 4 ] , [ 9 , 5 , 8 , 2 ] , [ 6 , 3 , 8 , 1 ] , [ 5 , 8 , 9 , 3 ] ] ; func ( a ) ;