program testQuickSort ! PURPOSE - to test the QuickSort implicit none integer :: n, m, i real,allocatable, dimension(:) :: nums real :: ran_num ! Read in a number - N write(*,*) 'Pls give the length (N) of the array (N should be the integer times of 5)' read(*,*) n allocate(nums(n)) ! Generate the random array of the length N in the scope of (0 to N) do i=1,n call random_number(ran_num) nums(i) = ran_num*n end do ! Print the Original array before the sorting write(*,*) '-------------------------------------------' write(*,*) 'The original Array (left to right):' m = 0 do while (m <n) write(*,'(5f11.4)') nums(m+1:m+5) m = m + 5 end do !Sort the array call QuickSort(nums,n) !Print the Array after the sorting write(*,*) '-------------------------------------------' write(*,*) 'The sorted Array (left to right):' m = 0 do while (m <n) write(*,'(5f11.4)') nums(m+1:m+5) m = m + 5 end do pause end program !------------------------------------ recursive subroutine QuickSort(A, n) ! PURPOSE: Quick sort an array A ! AUTHOR : Yongli Wu, 23/11/2018 ! INPUTS : 1) A - the array to be sorted ! 2) n - the length of the array A implicit none integer,intent(in) :: n real, intent(in out), dimension(n) :: A real:: V integer :: i, n_low, n_high, n_equal real, dimension(n):: low, high, equal n_low = 0; n_high=0; n_equal=0 if (n>1) then V = A(1) do i=1, n if (A(i)<V) then n_low = n_low+1 low(n_low) = A(i) elseif (A(i) > V) then n_high = n_high+1 high(n_high) = A(i) else n_equal = n_equal+1 equal(n_equal) = A(i) end if end do if (n_low>1) call QuickSort(low(1:n_low),n_low) if (n_high>1)call QuickSort(high(1:n_high),n_high) if(n_low>0) A(1:n_low) = low(1:n_low) if(n_equal>0) A(n_low+1:n_low+n_equal) = equal(1:n_equal) if(n_high>0) A(n_low+n_equal+1:n) = high(1:n_high) return else return end if end subroutine
说明: 因为插入代码的模板都没有FORTRAN,所以代码显示的关键字有些问题,但结构没变。
!-------------------------------------------------------------
测试结果如下: