尝试实现一个简单的冒泡排序。代码如下:
def bubble(array)
start = 0
sorted = []
while start < array.length - 1
if array[start] > array[start + 1]
array[start], array[start + 1] = array[start + 1], array[start]
else
end
start += 1
end
return array
end
print bubble([4,8,2,6,7,1])
我得到的输出是:
[4, 2, 6, 7, 1, 8]
我的代码哪里有问题?
首先,如果您打算使用sorted
,您应该避免修改array
,而是使用副本。您需要重复遍历数组,直到没有任何项是无序的,例如:
def bubble(array)
sorted = array.dup
finished = false
until finished
start = 0
finished = true
while start < sorted.length - 1
if sorted[start] > sorted[start + 1]
sorted[start], sorted[start + 1] = sorted[start + 1], sorted[start]
finished = false
end
start += 1
end
end
return sorted
end
尽管我想指出显式return
在Ruby中相对不受欢迎;您可以简单地将sorted
作为相同语义的最后一行。