首页 >

随机打乱数组之洗牌算法

作者:fcode  日期:10-28
来源:xjt@Fcode研讨团队
如下代码,将 1-10 的数组打乱,输出可能为:

9 4 2 3 10 7 8 5 6 1

Program www_fcode_cn
  Implicit None 
  Integer , parameter :: N = 10
  integer :: i
  integer :: a(N) = (/(i,i=1,N)/) 
  call Random_Seed()
  call Shuffle(a)
  write(*, "(10(i3))") a
 
contains
 
  Subroutine Shuffle( D )
    Implicit None
    Integer, Intent( INOUT ) :: D(:)
    integer :: i , p , t
    real :: r 
    Do i = size( D ) , 2 , -1
      call Random_Number( r )
      p = int( r * i ) + 1
      t = D( p )
      D( p ) = D( i )
      D( i ) = t
    End Do 
  End Subroutine Shuffle
 
End Program www_fcode_cn
常规|工具|专业|读物|
代码|教学|算法|
首页 >
FortranCoder手机版-导航