PROGRAM Selection_Sort
! This program implements Selection Sort on a run-time array.
IMPLICIT NONE
INTEGER :: I, N, Smallest_Location
REAL, DIMENSION(:), ALLOCATABLE :: A
REAL, DIMENSION(1) :: Loc_Array
REAL :: Smallest
! 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
! 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.
!=====================
! 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)
END PROGRAM Selection_Sort