PROGRAM Gen_Selection_Sort
! This program implements Selection Sort on a run-time array.
IMPLICIT NONE
INTEGER :: I, Smallest_Location, Lower_Ind_A, Upper_Ind_A
REAL, DIMENSION(:), ALLOCATABLE :: A
REAL, DIMENSION(1) :: Loc_Array
REAL :: Smallest
! Now read the lower and upper indices of array A.
PRINT *, "Enter lower and upper indices of A:"
READ *, Lower_Ind_A, Upper_Ind_A
! Now allocate memory for array A:
ALLOCATE(A(Lower_Ind_A:Upper_Ind_A))
! Now read elements of A.
PRINT *, "Enter elements of A. Notice that &
&there are ", Upper_Ind_A-Lower_Ind_A+1, " of them."
READ *, A
! Now we start the sorting process.
! =======================
! Selection Sort starts here.
DO I=Lower_Ind_A, Upper_Ind_A-1
! First we find the minimum value in the subarray A(I:Upper_Ind_A).
Smallest=MINVAL(A(I:Upper_Ind_A))
! Now we find the location of the first occurance of the
! minimum value with respect to the subarray A(I:Upper_Ind_A).
! Notice that the function MINLOC returns a
! one-dimensional array.
Loc_Array=MINLOC(A(I:Upper_Ind_A))
! 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 Gen_Selection_Sort