首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fortran排序-内存安全冲突

fortran排序-内存安全冲突
EN

Stack Overflow用户
提问于 2014-07-16 20:30:13
回答 1查看 85关注 0票数 1

我正在尝试编写一个程序(通过修改另一个适用于一维数组的程序),它对数组(2D)第二列中的元素进行排序。

代码语言:javascript
复制
    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 

编译没有问题,但不起作用。它只显示未排序数组的元素,然后显示有关内存安全冲突的信息。哪里出错了?提前谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-16 20:45:13

您没有递归的下限,并且试图将1x2数组细分为第一个维度.一个简单的if语句解决了这个问题:

代码语言:javascript
复制
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

输出:

代码语言:javascript
复制
 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  
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24790098

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档