有人可以解释这段代码吗?我从练习的解决方案部分得到它,所以它确实运行了。为什么不sorted
比较 using ==
,为什么sorted = false
需要添加sorted
after until
?
def bubble_sort(arr)
sorted = false
until sorted
sorted = true
(arr.count - 1).times do |i|
if arr[i] > arr[i + 1]
arr[i], arr[i + 1] = arr[i + 1], arr[i]
sorted = false
end
end
end
arr
end
我本来希望代码是这样的:
sorted = false
until sorted == true do
但是,当我尝试用它替换它时,出现以下错误:
eval):12: (eval):12: compile error (SyntaxError)
(eval):3: syntax error, unexpected kDO_COND, expecting kEND
(arr.count - 1).times do |i|
^
(eval):12: syntax error, unexpected kEND, expecting $end
这是出现错误的完整代码:
def bubble_sort(arr)
sorted = false
until sorted == true
(arr.count - 1).times do |i|
if arr[i] > arr[i + 1]
arr[i], arr[i + 1] = arr[i + 1], arr[i]
sorted = false
end
end
end
arr
end