PROGRAM Selection_Sort_SUB

! This program includes a SUBROUTINE which implements

! Selection Sort on a run-time array.

 

IMPLICIT NONE

INTEGER :: N

REAL, DIMENSION(:), ALLOCATABLE :: A

 

! Now read the size of array A. Notice that the indices start at 1.

PRINT *, "Enter size of array A:"

READ *, N

 

! Now allocate memory for array A:

ALLOCATE(A(N))

 

! Now read elements of A.

PRINT *, "Enter elements of A. Notice that there are ", N, " of them."

READ *, A

CALL Sel_Sort_SUB(A)

! Now we print the sorted array:

PRINT *, A

! Now free memory allocated for A.

! Notice that since Loc_Array is a compile-time array,

! then you canNOT include a statement like DEALLOCATE(Loc_Array).

! You use DEALLOCATE and ALLOCATE only for run-time arrays.

DEALLOCATE(A)

 

CONTAINS

SUBROUTINE Sel_Sort_SUB(A)

! Perform Selection Sort.

! Input : array A.

! Output : array A.

REAL, DIMENSION(:), INTENT(INOUT) :: A

INTEGER :: I, N,  Smallest_Location

REAL, DIMENSION(1) :: Loc_Array

REAL :: Smallest

 

                        N=SIZE(A)

 

! Now we start the sorting process.

! =======================

! Selection Sort starts here.

DO I=1, N-1

                                    ! First we find the minimum value in the subarray A(I:N).

                                    Smallest=MINVAL(A(I:N))

                                    ! Now we find the location of the first occurance of the

! minimum value with respect to the subarray A(I:N).

                                    ! Notice that the function MINLOC returns a

                                    ! one-dimensional array.

                                    Loc_Array=MINLOC(A(I:N))

                                    ! Now we find the location of the first occurance of the

                                    ! minimum value with respect to the array A.

                                    Smallest_Location=Loc_Array(1)+I-1

                                    ! Now swap the element whose index is I with the

                                    ! smallest element.

                                    A(Smallest_Location)=A(I)

                                    A(I)=Smallest

END DO

! Selection Sort Ends here.

!=====================

 

END SUBROUTINE Sel_Sort_SUB

 

END PROGRAM Selection_Sort_SUB