我正在阅读算法复杂性文本的介绍,作者有几种不同语言的例子,我已经能够遵循这些例子.然后在关键时刻,他给我打了这个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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
所以基本上,所有代码m = a[ 0 ]都b << m只是找到最小的元素a,并将其移动到b.那种情况发生了n.
因此,这样做是将n最小的元素移动a到b.
| 归档时间: |
|
| 查看次数: |
180 次 |
| 最近记录: |