Skip to main content

Sort array ascending in FORTRAN

Short answer

Read ten integers into array, sort them using bubble sort (two nested loops comparing adjacent elements and swapping if left larger). Print sorted list. Example: input 42 7 19 3 88 25 1 56 12 30 yields 1 3 7 12 19 25 30 42 56 88.

Write a program in FORTRAN to read an array containing N elements, sort this data in ascending order and display the result. (Read ten integer numbers, store them in array, arrange them in ascending order and display the sorted list.)

Method. Ten integers are read into the array A with an implied DO. Bubble sort is used: in each pass adjacent elements are compared and exchanged if the left one is larger. After pass I the largest I values are in their final places at the end, so 9 passes are enough for 10 elements. The sorted list is printed with an implied DO. (For N elements read N first and use DO 20 I = 1, N-1, DO 10 J = 1, N-I.)

      PROGRAM SORTAS
      INTEGER A(10), I, J, T
      PRINT *, 'ENTER TEN INTEGERS'
      READ *, (A(I), I = 1, 10)
      DO 20 I = 1, 9
         DO 10 J = 1, 10 - I
            IF (A(J) .GT. A(J+1)) THEN
               T = A(J)
               A(J) = A(J+1)
               A(J+1) = T
            END IF
   10    CONTINUE
   20 CONTINUE
      PRINT *, 'SORTED LIST IN ASCENDING ORDER:'
      PRINT *, (A(I), I = 1, 10)
      STOP
      END

Sample: input 42 7 19 3 88 25 1 56 12 30 gives 1 3 7 12 19 25 30 42 56 88.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 11 questions →