    PROGRAM nag_sort_ex05

      ! Example Program Text for nag_sort
      ! NAG fl90, Release 4. NAG Copyright 2000.

      ! .. Use Statements ..
      USE nag_examples_io, ONLY : nag_std_in, nag_std_out
      USE nag_write_mat, ONLY : nag_write_gen_mat
      USE nag_sort, ONLY : nag_invert_perm, nag_check_perm, nag_rank_mat
      ! .. Implicit None Statement ..
      IMPLICIT NONE
      ! .. Local Scalars ..
      INTEGER :: i, m, n
      ! .. Local Arrays ..
      INTEGER, ALLOCATABLE :: a(:,:), rank(:)
      ! .. Executable Statements ..
      WRITE (nag_std_out,*) 'Example Program Results for nag_sort_ex05'
      WRITE (nag_std_out,*)

      READ (nag_std_in,*)          ! Skip heading in data file
      READ (nag_std_in,*) m, n

      ALLOCATE (rank(m),a(m,n))    ! Allocate storage

      READ (nag_std_in,*) (a(i,:),i=1,m)

      ! Rank the matrix by row, in ascending order

      CALL nag_rank_mat(a,rank)

      ! Check the validity of the permutation
      IF (nag_check_perm(rank)) THEN

        ! Invert the permutation

        CALL nag_invert_perm(rank)

        CALL nag_write_gen_mat(a(rank(:),:),title='Matrix sorted by rows')

      END IF

      DEALLOCATE (a,rank)          ! Deallocate storage

    END PROGRAM nag_sort_ex05
