next up previous
Next: Bubble sort: Version 2 Up: CS101 Lecture 5 Previous: Looping Control Structure

Bubble sort Version 1

! Program for sorting 500 or less numbers
!   Written by siva@cse.iitb.ernet.in, Aug 7, 2000
! This file uses a variation of the "bubble" sort approach.
! It makes repeated passes through the array exchanging
! marks[i] and marks [i + 1] if they are out of order.
! until no more exchanges are possible.
Program mysort

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

! the flag that checks if any swaps are made
Logical :: swapflag

! a variable to use as counter when looping
Integer :: i

! another to count how many swaps are done
Integer :: 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.

outer: DO
!initialize swapflag to fasle
 swapflag = .false.
! now go through the array seeing if any swap is needed.
 inner: Do i = 1, size - 1
    if ((marks(i) > marks(i+1))) Then
       ! swap the marks
        tmp = marks(i+1)
        marks(i+1) = marks(i)
        marks(i) = tmp
        nswap = nswap + 1
       ! since we have swapped, we set swapflag to true
        swapflag = .true.
     end if
     End Do inner
! if no swaps were needed, then array is in sorted order. 
  if (.NOT. swapflag) EXIT
End Do outer


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

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

End Program mysort



G. Sivakumar 2000-08-13