PROGRAM TRI
   IMPLICIT NONE

   ! Declarations
   INTEGER :: n, i, j, jmin
   REAL :: umax, umin
   REAL, DIMENSION(100) :: u, v
   REAL :: val_max

   ! Recuperation des donnees du fichier don.dat
   CALL lecture(n,u)
   umax = val_max(n,u)
   DO i = 1, n            
        ! Recherche du min + indice de u
        CALL recherche_min(n,u,umax,umin,jmin)
        v(i) = umin                ! Met la valeur min dans v
        u(jmin) = umax         ! Ecrase la valeur min de u
   END DO
   ! Ecriture dans res.dat
   CALL ecriture(n,v)   

END PROGRAM TRI

FUNCTION val_max(k,p)
   IMPLICIT NONE

   INTEGER, INTENT(IN) :: k
   REAL, DIMENSION(100), INTENT(IN) :: p
   REAL :: val_max
   !REAL :: valeur
   INTEGER :: i

   val_max = p(1) 
   DO i = 2, k
       IF( p(i) >= val_max ) THEN
             val_max = p(i)
        END IF
   END DO

END FUNCTION val_max

SUBROUTINE lecture(n,u)

   IMPLICIT NONE
   INTEGER, INTENT(OUT) :: n
   REAL, DIMENSION(100), INTENT(OUT) :: u
   INTEGER :: i

   OPEN(10, file='don.dat') 
   READ(10,*) n
   DO i = 1, n
      READ(10,*) u(i)
   END DO
   CLOSE(10)

END SUBROUTINE lecture

SUBROUTINE recherche_min(n,u,umax,umin,jmin)

   IMPLICIT NONE
   INTEGER, INTENT(IN) :: n
   REAL, DIMENSION(100), INTENT(IN) :: u
   REAL, INTENT(IN) :: umax
   REAL, INTENT(OUT) :: umin
   INTEGER, INTENT(OUT) :: jmin
   INTEGER :: i

   jmin = 1
   umin = umax
   DO i = 1, n
       IF ( u(i) <= umin ) THEN
             umin = u(i)
             jmin = i
       END IF
   END DO

END SUBROUTINE recherche_min

SUBROUTINE ecriture(n,v)

   IMPLICIT NONE
   INTEGER, INTENT(IN) :: n
   REAL, DIMENSION(100), INTENT(IN) :: v
   INTEGER :: i

   OPEN(10, file='res.dat')
   WRITE(10,*) n
   DO i = 1, n
      WRITE(10,*) v(i)
   END DO
   CLOSE(10)

END SUBROUTINE ecriture
