我无法理解这个红宝石冒泡排序实现的部分内容?

时间:2016-02-21 23:06:40

标签: ruby

我试图理解ruby中的以下冒泡排序实现。我不明白的主要是使用sorted变量。 我评论了我觉得最令人困惑的部分,我非常感谢sorted变量使用的解释。

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

3 个答案:

答案 0 :(得分:2)

until sorted就像在说while !sorted

考虑到这一点,我认为这应该更有意义。

Ruby对if语句有类似的构造。你可以说 unless foo表示与if !foo相同。有时这些类型的表达式会让人感到困惑,因为它们可能是双重否定。

但是如果你只是大声读出代码那就应该有意义了......

直到数组排序...继续排序...

答案 1 :(得分:1)

你走在正确的轨道上,但until关键字的行为与你的直觉相反。代码

until X
    action

应该在“X成立之前阅读,重复action”,换句话说,只要action为假,就会重复X。“

答案 2 :(得分:0)

def bubble_sort(arr)
    sorted = false  #sorted varriable is equal to false
    until sorted  #until sorted variable is true, this code will run
        sorted = true #sorted variable is now 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 #sorted variable is now set to false, so loop will run again.
            end
        end
    end
    arr
end