! Program for sorting 500 or less numbers
!   Written by siva@cse.iitb.ernet.in, Aug 7, 2000
! This file uses the naive "bubble" sort approach that
! makes repeated passes through the array pushing the
! biggest number to the bottom
Program mysort

! declare the array for reading input. assumed size < 500
Integer, dimension(500) :: marks
Integer :: size

! some variables to use as counters when looping
Integer :: i,j

! count how many swaps
Integer :: nswap
nswap = 0
!first read in size and marks
Read (*,*) size

If ((size > 500)) Then
   Write (*,*) "Sorry we handle max of 500 numbers"
   Stop
End If

write (*,*) "reading ", size, " numbers."

DO i = 1, size
 Read (*,*) marks(i)
End Do

write(*,*) "Have Read in ", size, " numbers. Thanks."


!keep going through the array and exchanging any out of
!order elements until no exchange is possible.
j = size
outer: DO
 if (j == 1) EXIT
! now go through the array pushing biggest number to bottom
 inner: Do i = 1, j - 1
    if ((marks(i) > marks(j))) Then
       ! swap the marks
        tmp = marks(j)
        marks(j) = marks(i)
        marks(i) = tmp
        nswap = nswap + 1
     end if
     End Do inner
! now marks(j) is bigger than all above. repeat for next j
  j = j - 1
End Do outer

! when we reach here it is sorted. print it out
DO i = 1, size
 Write (*,*) marks(i)
End Do

Write (*,*) "This needed ", nswap, " swaps to sort the array."

End Program mysort
