我正在尝试编写一个程序(通过修改另一个适用于一维数组的程序),它对数组(2D)第二列中的元素进行排序。
module qsort_c_module
implicit none
public :: QsortC
private :: Partition
contains
recursive subroutine QsortC(A)
real, intent(in out), dimension(:,:) :: A
integer :: iq
call Partition(A, iq)
call QsortC(A(:iq-1,:2))
call QsortC(A(iq:,:2))
end subroutine QsortC
subroutine Partition(A, marker)
real, intent(in out), dimension(:,:) :: A
integer, intent(out) :: marker
integer :: i, j
real :: temp
real :: x ! pivot point
x = A(1,2)
i= 0
j= size(A,1) + 1
do
j = j-1
do
if (A(j,2) >= x) exit
j = j-1
end do
i = i+1
do
if (A(i,2) <= x) exit
i = i+1
end do
if (i < j) then
! exchange A(i) and A(j)
temp = A(i,2)
A(i,2) = A(j,2)
A(j,2) = temp
elseif (i == j) then
marker = i+1
return
else
marker = i
return
endif
end do
end subroutine Partition
end module qsort_c_module
program sortdriver
use qsort_c_module
implicit none
integer i
integer templ
real, dimension(4,2) :: myarray
myarray(1,1)=1
myarray(2,1)=2
myarray(3,1)=3
myarray(4,1)=4
myarray(1,2)=11
myarray(2,2)=22
myarray(3,2)=22
myarray(4,2)=33
write(*,*) 'Before sort'
do i=1,4
write(*,*) real ( myarray(i,:) )
end do
call QsortC(myarray)
write(*,*) 'After sort'
do i=1,4
write(*,*) real( myarray(i,:) )
end do
end program sortdriver 编译没有问题,但不起作用。它只显示未排序数组的元素,然后显示有关内存安全冲突的信息。哪里出错了?提前谢谢你的帮助。
发布于 2014-07-16 20:45:13
您没有递归的下限,并且试图将1x2数组细分为第一个维度.一个简单的if语句解决了这个问题:
recursive subroutine QsortC(A)
real, intent(in out), dimension(:,:) :: A
integer :: iq
if (size(A,1) .eq. 1) return
call Partition(A, iq)
call QsortC(A(:iq-1,:2))
call QsortC(A(iq:,:2))
end subroutine QsortC输出:
Before sort
1.00000000 11.0000000
2.00000000 22.0000000
3.00000000 22.0000000
4.00000000 33.0000000
After sort
1.00000000 33.0000000
2.00000000 22.0000000
3.00000000 22.0000000
4.00000000 11.0000000 https://stackoverflow.com/questions/24790098
复制相似问题