gpt4 book ai didi

algorithm - Fortran 冒泡排序算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:33:55 25 4
gpt4 key购买 nike

我在编译冒泡排序算法时遇到问题,我不知道自己做错了什么。如果有人帮助我,我将不胜感激。

这是代码:

program bubble

integer, dimension(6) :: vec
integer :: temp, bubble, lsup, j

read *, vec !the user needs to put 6 values on the array
lsup = 6 !lsup is the size of the array to be used

do while (lsup > 1)
bubble = 0 !bubble in the greatest element out of order
do j = 1, (lsup-1)
if vet(j) > vet(j+1) then
temp = vet(j)
vet(j) = vet(j+1)
vet(j+1) = temp
bubble = j
endif
enddo
lsup = bubble
enddo
print *, vet
end program

谢谢!

最佳答案

您的代码中存在各种问题:

  • 变量不能与程序同名
  • 条件句缺少括号
  • 打字错误:vet 而不是 vec

这是一个干净的解决方案:

program bubble_test

implicit none
integer, dimension(6) :: vec
integer :: temp, bubble, lsup, j

read *, vec !the user needs to put 6 values on the array
lsup = 6 !lsup is the size of the array to be used

do while (lsup > 1)
bubble = 0 !bubble in the greatest element out of order
do j = 1, (lsup-1)
if (vec(j) > vec(j+1)) then
temp = vec(j)
vec(j) = vec(j+1)
vec(j+1) = temp
bubble = j
endif
enddo
lsup = bubble
enddo
print *, vec
end program

您的编码可以进一步改进...参见this example .

关于algorithm - Fortran 冒泡排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19550621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com