Sort the major diagonal of the matrix | Function to sort the major diagonal of the matrix ; Loop to find the ith minimum element from the major diagonal ; Loop to find the minimum element from the unsorted matrix ; Swap to put the minimum element at the beginning of the major diagonal of matrix ; Loop to print the matrix ; Driven Code ; Sort the major Diagonal
function sortDiagonal ( a , M , N ) { for ( var i = 0 ; i < M ; i ++ ) { var sm = a [ i ] [ i ] ; var pos = i ; for ( var j = i + 1 ; j < N ; j ++ ) { if ( sm > a [ j ] [ j ] ) { sm = a [ j ] [ j ] ; pos = j ; } } temp = a [ i ] [ i ] a [ i ] [ i ] = a [ pos ] [ pos ] a [ pos ] [ pos ] = temp } for ( var i = 0 ; i < M ; i ++ ) { for ( var j = 0 ; j < N ; j ++ ) document . write ( a [ i ] [ j ] + " " ) ; document . write ( " " ) ; } } var a = [ [ 4 , 2 ] , [ 3 , 1 ] ] ; sortDiagonal ( a , 2 , 2 ) ;