回 帖 发 新 帖 刷新版面

主题:Fortran 如何随机排列数组

例如有一个数组 node=(/1,2,3,4,5/), 如何随机排列数组中的5个数从而得到新的数组?


谢谢!

回复列表 (共2个回复)

沙发

subroutine rand_sort(array, size)
implicit none
integer, intent(in) :: size
real, dimension(size), intent(in out) :: array
real, allocatable :: x(:)
real temp
integer i, j

! generate random array
allocate (x(size))
call random_seed()
call random_number(x)

! sort x and array
do i = 1,size-1
    do j = i+1, size
        if(x(i).GT.x(j)) then
            temp = x(i)
            x(i) = x(j)
            x(j) = temp
            temp = array(i)
            array(i) = array(j)
            array(j) = temp
        end if
    end do
end do
deallocate(x)
return
end subroutine rand_sort

program test
implicit none
integer i
real, dimension(10) :: cc = (/(I,I=1,10)/)
write(*,"(10F5.1,/)") cc
call rand_sort(cc,10)
write(*,"(10F5.1)") cc
pause
stop
end program test

板凳

厉害!

我来回复

您尚未登录,请登录后再回复。点此登录或注册