Skip to main content

SORT2.F95

	PROGRAM SORT2
!
!  Purpose: to sort and display a one-dimensional array of up to 100 
!           random numbers.
!
!  With illustration of the use of allocatable arrays.
!
	IMPLICIT NONE
	INTEGER:: N,I,J,I_LARGEST
	REAL, ALLOCATABLE:: RANDOM(:)
	REAL:: LARGEST
!
!  First: read the number of random numbers should be calculated, N, and
!  check that this number makes sense.
	WRITE(*,10,ADVANCE='NO')
   10	FORMAT('Please specify how many of random numbers should be', &
           ' calculated: ')
	READ(*,*)N
	IF(N > 100)THEN
	   WRITE(*,11)
   11      FORMAT('This number should not exceed 100.')
	   STOP
	ELSE IF(N < 1)THEN
	   WRITE(*,12)
   12      FORMAT('This number should not be 0 or negative.')
	   STOP
	END IF
!
!  Set the size of the vector RANDOM in the memory
	ALLOCATE(RANDOM(N))
!
!  Fill the vector RANDOM with random numbers.
	DO I=1,N
	   CALL RANDOM_NUMBER(RANDOM(I))
	END DO
!
!  Sort RANDOM into descending order
	DO J=1,N
!  For each J, find the largest element of RANDOM between RANDOM(J) and
!  RANDOM(N). Store this largest element in LARGEST; I_LARGEST is its
!  index within the vector RANDOM.
	   LARGEST=RANDOM(J)
           I_LARGEST=J
	   DO I=J+1,N               
	     IF(RANDOM(I) > LARGEST)THEN
	        I_LARGEST=I
	        LARGEST=RANDOM(I)
	     END IF
	   END DO
! Swap the largest element found with RANDOM(J). Note that the next two
! lines should not be interverted !
 	   RANDOM(I_LARGEST)=RANDOM(J)
	   RANDOM(J)=LARGEST
	END DO
!
!  Display the sorted vector on the screen using an implied DO loop. With the
!  FORMAT speficied, only one number is displayed on each line of output.
	WRITE(*,100)(RANDOM(I),I=1,N)
  100	FORMAT(E15.7)
!
	END PROGRAM SORT2