- #1
chemengstuden
- 6
- 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
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