I don't understand logical variables in fortran

  • Context: Comp Sci 
  • Thread starter Thread starter chemengstuden
  • Start date Start date
  • Tags Tags
    Fortran Variables
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 4K views
chemengstuden
Messages
6
Reaction score
0
I found the following program in a textbook and I don't understand how logical variables are used for the sorting function. I understand that variables is supposed to tell the program to keep functioning until the sorting is complete, I just don't understand the specifics. The logical variable "sorted" starts off false what does that mean exactly, and what happens to it in the do while loop.

IMPLICIT NONE
INTEGER, PARAMETER :: N = 100 ! size of list
REAL, DIMENSION(N) :: List ! list to be sorted
INTEGER I ! counter
REAL R ! random number

DO I = 1, N
CALL Random_Number( R )
List(I) = INT( N * R + 1 ) ! random integers in range
END DO

PRINT 10, List ! print unsorted list
10 FORMAT( 13F6.0 )

CALL Bubble_Sort( List ) ! sort

PRINT 10, List ! print sorted list

CONTAINS
SUBROUTINE Bubble_Sort( X )
REAL, DIMENSION(:), INTENT(INOUT) :: X ! list
INTEGER :: Num ! size of list
REAL Temp ! temp for swo
INTEGER J, K ! counters
LOGICAL Sorted ! flag to detect when sorted

Num = SIZE(X)
Sorted = .FALSE. ! initially unsorted
K = 0 ! count the passes

DO WHILE (.NOT. Sorted)
Sorted = .TRUE. ! they could be sorted
K = K + 1 ! another pass
DO J = 1, Num-K ! fewer tests on each pass
IF (X(J) > X(J+1)) THEN ! are they in order?
Temp = X(J) ! no ...
X(J) = X(J+1)
X(J+1) = Temp
Sorted = .FALSE. ! a swop was made
END IF
END DO
END DO

END SUBROUTINE
END
 
Physics news on Phys.org
SORTED starts out FALSE causing the while loop to execute during the first pass.

In the loop itself it supposes the data may already be sorted by setting SORTED = TRUE.
Then as it passes through the loop it checks whether it needs to re-arrange anything. If it does, then it sets SORTED = FALSE. This causes the loop to execute again. This continues until the loop doesn't need to swap anything so it doesn't set SORTED = FALSE on that pass which causes the while loop to finish.
 
In addition to what LCKurtz already said, a DO WHILE loop such as this:

DO WHILE (<boolean expression>)
.
.
.
END DO

executes the statements in the loop body if <boolean expression> evaluates to true.

If SORTED is false, then the expression .NOT. SORTED evaluates to TRUE, so the loop begins an iteration, and SORTED is set to TRUE. If it turns out that X(J) > X(J + 1), then SORTED gets reset to FALSE. On the other hand, if no swaps need to be made in a complete pass through the array, then SORTED doesn't get reset to FALSE (i.e., is still TRUE). This means that when control passes back up to the WHILE loop, .NOT SORTED is FALSE, and the loop does not execute.