mee mee
mee mee

Reputation: 557

sorting arrays by rows in FORTRAN

I need to sort rows of a matrix in ascending/descending order. In matlab I can do quite easily as follows:

A=[3 1 0;2 1 9;0 4 8]
sortrows(A,1)

so it will sort the rows in column "1" and the other columns will follow accordingly. But I need to do this in FORTRAN. And I am not very familiar with FORTRAN. Can anyone advise me how to do this in FORTRAN. Thanks.

Upvotes: 1

Views: 11361

Answers (1)

roygvib
roygvib

Reputation: 7395

Although Fortran does not have sorting intrinsics, the code may become a bit simpler if you use minloc function to find the smallest element in the first column and swapping the corresponding row with the current one iteratively, for example:

program main
    implicit none
    integer :: A(3,3), buf(3)
    integer :: nsize, irow, krow

    nsize = 3
    A( 1, : ) = [ 3, 1, 0 ]
    A( 2, : ) = [ 2, 1, 9 ]
    A( 3, : ) = [ 0, 4, 8 ]

    do irow = 1, nsize
        krow = minloc( A( irow:nsize, 1 ), dim=1 ) + irow - 1

        buf( : )     = A( irow, : )
        A( irow, : ) = A( krow, : )
        A( krow, : ) = buf( : )
    enddo
end

which gives

A( 1, : ) = 0  4  8
A( 2, : ) = 2  1  9
A( 3, : ) = 3  1  0

Upvotes: 8

Related Questions