对Ruby中的数组使用冒泡排序方法
问题描述:
我正在尝试将Bubble排序方法实现为Ruby的一个简单编码问题,但遇到了一些麻烦。我了解的想法是先查看第一个元素的值,然后将其与第二个元素的值进行比较,然后相应地交换它们,但我似乎无法在实际问题中做到这一点。有人愿意提供一个简短的示例说明如何在Ruby中工作吗?
I'm trying to implement the Bubble sort method into an easy coding problem for Ruby, but I'm having some trouble. I understand the idea is to look at the value of the first element and compare it to the value of the second element and then swap them accordingly, but I can't seem to do it in an actual problem. Would anyone be willing to provide a brief example of how this might work in Ruby?
答
使用a正确的气泡排序实现while循环
Correct implementation of the bubble sort with a while loop
def bubble_sort(list)
return list if list.size <= 1 # already sorted
swapped = true
while swapped do
swapped = false
0.upto(list.size-2) do |i|
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i] # swap values
swapped = true
end
end
end
list
end