0

I'm reading an introduction to algorithm complexity text and the author has examples in several different languages, which I have been able to follow along. Then at the crucial moment he hits me this Ruby code which is Greek to me. Can someone explain what this code does?

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
4

1 回答 1

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

所以基本上,所有的代码 from m = a[ 0 ]tob << m只是找到 中的最小元素a,并将其移动到b. 这种情况经常发生n

因此,它所做的是将n最小的元素从移动ab

于 2013-06-14T01:47:09.837 回答