program SortData_2
Implicit None
Integer N
Real Grades(1000)
C Open Files
Open(unit=1,file='data.in',type='old')
Open(unit=2,file='data.out2',type='unknown')
Call GetData(Grades, N)
Call SelectSort(Grades, N)
Call WriteFile(Grades, N)
end
C------------------------GetData-------------------------------------
Subroutine GetData(Grade, Num_Grades)
C
C Get the input data from the prespecified file
C Return an array of grades and the number of elements in the array
C
Implicit none
Integer i, Num_Grades
Real Grade(1)
Do i = 1, 1000000
read(1,*,end=10) Grade(i)
end do
10 Num_Grades = i - 1
return
end
C------------------------SelectSort-------------------------------------
Subroutine SelectSort(Elements, Num_Elements)
C
C Sort an array of real values (Elements) by selection sort
C Return the elements sorted into increasing order
C
Implicit none
Integer i, j
Integer Num_Elements, Position
Real Elements(1), Small, temp
Do i = 1 , Num_Elements - 1 ! start outer loop
Small = Elements(i) ! assume current element is smallest
Position = i
Do j = i+1, Num_Elements ! consider remainder of array
If (Elements(j) .LT. Small) Then ! check if current element
Small = Elements(j) ! is smaller than the smallest
Position = j ! found thusfar
end if
end do
temp = Elements(Position) ! switch smallest element
Elements(Position) = Elements(i) ! with current element
Elements(i) = temp
end do
return
end
C------------------------WriteFile-------------------------------------
Subroutine WriteFile(Elements, Num_Elements)
C
C Write the final sorted array out to a different file
C
Implicit none
Integer i, Num_Elements
Real Elements(1)
Do i = 1,Num_Elements
write(2,*) Elements(i)
end do
return
end