CSC 272 - Software II: Principles of Programming Languages

Dr. R. M. Siegfried

A FORTRAN Program to sort an array of integers

c     All lines beginning with a "C" in column 1 are comments
c     Declare an array of integers and initialize 
c
      integer array(8)/25, 57, 48, 37, 12, 92, 86, 33/
c
c     Declare lenarray as a constant Begin with an "L
c     to ensure that it is an integer

      parameter (lenarray = 8)
c
      write(*,501)
  501 format(' Before sorting:')

c     For i := 1 to LenArray Step 4
      do 101 i = 1, lenarray, 4
c       Print the numbers four to a line
c       Continue the statement on the next line
        write(*, 502) array(i), array(i+1), array(i+2),
     1       array(i+3)
c
c       Print a two-digit integer and 4 blanks 4 times
  502   format(' ', 4(i2, 4x))
  101 continue
c
      call bubble(array, lenarray)
c
      write(*,503)
  503 format(' After sorting:')

      do 102 i = 1, lenarray, 4
        write(*, 502) array(i), array(i+1), array(i+2), array(i+3)
  102 continue

      end
c
c
c
      subroutine bubble(x, n)
      integer x(n), n, j, pass
      logical switch/.true./
c
c     FORTRAN-77 does not have a WHILE loop in the standard
c     so use the IF..THEN construction to create one.

      pass = 1
  201 if ((pass.lt.n).and.switch) then
 
       switch = .false.
c
c       For J := 1 to N-Pass DO
c
        do 202 j = 1, n-pass
          if (x(j) .gt. x(j+1)) then
            switch = .true.
            call swap(x(j), x(j+1))
          endif
  202   continue
        pass = pass + 1
        go to 201
      endif
      
      return
      end
c
c
c     All parameter passing is by reference
c
      subroutine swap(i, j)
      integer i, j, temp
c
      temp = i
      i = j
      j = temp
      return
      end

[Back to the FORTRAN Program Index]