我在理解这个ruby冒泡排序实现的部分方面遇到了困难?
我试图理解以下ruby中的冒泡排序实现。我不明白的主要问题是我在理解这个ruby冒泡排序实现的部分方面遇到了困难?,ruby,Ruby,我试图理解以下ruby中的冒泡排序实现。我不明白的主要问题是排序的变量的用法。 我已经对我认为最容易混淆的部分进行了注释,如果能解释一下排序的变量的用法,我将不胜感激 def bubble_sort(arr) sorted = false #set sorted to false because array is not yet sorted..correct? until sorted #this is where I get confused..this means un
排序的变量的用法。
我已经对我认为最容易混淆的部分进行了注释,如果能解释一下排序的变量的用法,我将不胜感激
def bubble_sort(arr)
sorted = false #set sorted to false because array is not yet sorted..correct?
until sorted #this is where I get confused..this means until false..right? Shouldn't it be until true?
sorted = true #this makes a little more sense. Now sorted = true, so until = false isn't satisfied
(arr.count - 1).times do |i|
if arr[i] > arr[i + 1]
arr[i], arr[i+1] = arr[i+1], arr[i]
sorted = false #so now sorted = false, shouldn't this mean the loop stops? How does the program go through more than one iteration of the until loop?
end
end
end
arr
end
直到排序
就像说while!已排序
考虑到这一点,我认为这应该更有意义
Ruby对if
语句有类似的构造。你可以说
除非foo
,这与如果相同!foo
。有时,这些类型的表达式令人困惑,因为它们可能是双重否定
然而,如果你只是大声读出代码,它应该是有意义的
在数组排序之前。。。继续对它排序…直到排序
就像在说的时候!已排序
考虑到这一点,我认为这应该更有意义
Ruby对if
语句有类似的构造。你可以说
除非foo
,这与如果相同!foo
。有时,这些类型的表达式令人困惑,因为它们可能是双重否定
然而,如果你只是大声读出代码,它应该是有意义的
在数组排序之前。。。继续排序…你在正确的轨道上,但是直到关键字的行为与你的直觉相反。代码
until X
action
应该读为“直到X
为真,重复action
,”或者,换句话说,“重复action
,只要X
为假。”你在正确的轨道上,但是until
关键字的行为与你的直觉相反。代码
until X
action
应读为“直到X
为真,重复action
,”或换句话说,“重复action
,只要X
为假。”