Sort Matrix in alternating ascending and descending order rowwise | Java 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
class GFG { static int N = 4 ; static void func ( int a [ ] [ ] ) { int i , j , k ; for ( i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { for ( j = 0 ; j < N ; j ++ ) { for ( k = j + 1 ; k < N ; ++ k ) { if ( a [ i ] [ j ] > a [ i ] [ k ] ) { int temp = a [ i ] [ j ] ; a [ i ] [ j ] = a [ i ] [ k ] ; a [ i ] [ k ] = temp ; } } } } else { for ( j = 0 ; j < N ; j ++ ) { for ( k = j + 1 ; k < N ; ++ k ) { if ( a [ i ] [ j ] < a [ i ] [ k ] ) { int temp = a [ i ] [ j ] ; a [ i ] [ j ] = a [ i ] [ k ] ; a [ i ] [ k ] = temp ; } } } } } for ( i = 0 ; i < N ; i ++ ) { for ( j = 0 ; j < N ; j ++ ) { System . out . print ( a [ i ] [ j ] + " ▁ " ) ; } System . out . print ( "NEW_LINE"); } } public static void main ( String [ ] args ) { int a [ ] [ ] = { { 5 , 7 , 3 , 4 } , { 9 , 5 , 8 , 2 } , { 6 , 3 , 8 , 1 } , { 5 , 8 , 9 , 3 } } ; func ( a ) ; } }