主题:Fortran 如何随机排列数组
lluvia
[专家分:0] 发布于 2013-01-18 11:18:00
例如有一个数组 node=(/1,2,3,4,5/), 如何随机排列数组中的5个数从而得到新的数组?
谢谢!
回复列表 (共2个回复)
沙发
heizaoniangao [专家分:310] 发布于 2013-01-18 13:58:00
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
我来回复