编辑代码

module bubble_sort_module
  implicit none

contains

  subroutine bubble_sort(arr, n)
    integer, intent(inout) :: arr(:)  ! 数组作为参数
    integer, intent(in)    :: n       ! 数组的长度
    integer                 :: i, j
    integer                 :: temp

    ! 外层循环控制排序的总轮数
    do i = 1, n-1
      ! 内层循环进行每轮的冒泡操作
      do j = 1, n-i
        if (arr(j) > arr(j+1)) then
          ! 交换元素
          temp = arr(j)
          arr(j) = arr(j+1)
          arr(j+1) = temp
        end if
      end do
    end do
  end subroutine bubble_sort

end module bubble_sort_module

program main
  use bubble_sort_module, only : bubble_sort
  implicit none

  integer, dimension(5) :: array = / 5, 3, 8, 4, 2 /  ! 使用数组构造器初始化数组
  integer :: n = size(array)

  ! 打印原始数组
  print *, 'Original array:'
  write(*, '(5I5)') array  ! 使用write语句格式化输出

  ! 调用冒泡排序函数
  call bubble_sort(array, n)

  ! 打印排序后的数组
  print *, 'Sorted array:'
  write(*, '(5I5)') array  ! 使用write语句格式化输出

end program main