Fortran Bubble Sort Algorithm

user2803219 picture user2803219 · Oct 23, 2013 · Viewed 9.8k times · Source

I'm with problems to compile a Bubble sort algorithm, I dont know what I'm doing wrong. I will appreciate so much if somebody helps me.

This is the code:

program bubble

   integer, dimension(6) :: vec 
     integer :: temp, bubble, lsup, j

      read *, vec !the user needs to put 6 values on the array
       lsup = 6 !lsup is the size of the array to be used

  do while (lsup > 1)
bubble = 0 !bubble in the greatest element out of order
      do j = 1, (lsup-1)
    if vet(j) > vet(j+1) then
    temp = vet(j)
    vet(j) = vet(j+1)
    vet(j+1) = temp
    bubble = j
      endif 
    enddo
    lsup = bubble   
enddo   
    print *, vet
end program

Thanks!

Answer

Alexander Vogt picture Alexander Vogt · Oct 23, 2013

You had various issues in your code:

  • a variable must not be name as the program
  • the conditional lacked paranthesis
  • typos: vet instead of vec

Here is a clean solution:

program bubble_test

  implicit none
  integer, dimension(6) :: vec 
  integer :: temp, bubble, lsup, j

  read *, vec !the user needs to put 6 values on the array
  lsup = 6 !lsup is the size of the array to be used

  do while (lsup > 1)
    bubble = 0 !bubble in the greatest element out of order
    do j = 1, (lsup-1)
      if (vec(j) > vec(j+1)) then
        temp = vec(j)
        vec(j) = vec(j+1)
        vec(j+1) = temp
        bubble = j
      endif 
    enddo
    lsup = bubble   
  enddo   
  print *, vec
end program

Your coding can be further improved... See this example.