fortran66のブログ

fortran について書きます。

挿入ソート改良

ここまで来ると更に簡単に。尻からではなく、頭から sort してゆく。

module m_isort2
    implicit none
    contains
    
    subroutine isort3y( x )
      real, intent(in out) :: x(:)
      integer :: j, k
      do k = 2, size(x)
        do j = 1, k - 1
          if ( x(k) < x(j) ) exit 
        end do
        x(j:k) = cshift( x(j:k), -1 )
      end do
      return
    end subroutine isort3y
  
  end module
 
  program sort2
    use m_isort2
    implicit none
    real, allocatable :: x(:)
    integer :: i 
    !
    allocate( x(100) )
    call random_seed()
    call random_number(x)
    call isort3y(x)
    print *, x
    do i = 1, size(x) - 1 ! check
      if (x(i) > x(i + 1) ) print *, 'error!', i
    end do
    stop
  end program sort2