有人可以解释这个Ruby代码的作用吗?

时间:2013-06-14 01:43:43

标签: ruby

我正在阅读算法复杂性文本的介绍,作者有几种不同语言的示例,我已经能够遵循这些示例。然后在关键时刻,他给我打了这个Ruby代码,这对我来说是希腊语。有人可以解释这段代码的作用吗?

b = []
n.times do
    m = a[ 0 ]
    mi = 0
    a.each_with_index do |element, i|
        if element < m
            m = element
            mi = i
        end
    end
    a.delete_at( mi )
    b << m
end

1 个答案:

答案 0 :(得分:5)

b = [] # b is a new array
n.times do # do this n times
    m = a[ 0 ] # m is the first element of a
    mi = 0 # mi (the index of m) is 0
    a.each_with_index do |element, i| # loop through a, with the index
        if element < m # if the element is less than m
            m = element # set m to the element
            mi = i # set mi to the element's index
        end
    end
    a.delete_at( mi ) # delete the element at index mi (which is m)
    b << m # append m to b
end

基本上,m = a[ 0 ]b << m的所有代码都只找到a中的最小元素,并将其移至b。这种情况发生n次。

因此,这样做会将n个最小元素从a移到b