我只是在寻求对我的Ruby实现泡沫排序算法的建设性批评。
class BubbleSorter < Object
def bubble_sort(list)
swaps = 0
# parse the list until it is sorted
until @sorted == true
# run the comparison of adjacent elements
for i in 0...(list.length - 1)
# if the first is greater than the second, swap them with parallel assignment
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i]
# increase the number of swaps performed in this run by 1
swaps += 1
end
# compare the next 2 elements
i += 1
end
# uncomment the following line to see each iteration:
# p list
# If any swaps took place during the last run, the list is not yet sorted
if swaps > 0
@sorted = false
# no swaps? Everything is in order
else
@sorted = true
end
# reset swap count for each run
swaps = 0
end
end
end发布于 2016-08-21 22:54:51
虽然你应该评论你的工作,但你的一些评论似乎是没有必要的。让我们看一些行,看看为什么:
# parse the list until it is sorted
until @sorted == true这句话似乎多余。您的代码行until @sorted == true读得很清楚,我可以理解您想要一直做一些事情,直到列表被排序。
# if the first is greater than the second, swap them with parallel assignment
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i]这段代码也很容易解释。如果你有评论,你应该解释你为什么这样做。然而,bubblesort是众所周知的,所以您可能甚至不需要对此发表评论。
# increase the number of swaps performed in this run by 1
swaps += 1再说一遍为什么?我可以阅读代码,很明显,您正在增加swaps的数量。我会省略的。
# compare the next 2 elements
i += 1基于if语句,我会知道这是i的目的。我会省略它,但它确实解释了为什么要增加i,所以这里有一些灰色区域。
最后写一些好的评论,让我们分析它们为什么是好的:
# If any swaps took place during the last run, the list is not yet sorted
if swaps > 0
@sorted = false
# no swaps? Everything is in order
else
@sorted = true它解释了为什么我们需要检查是否swaps > 0以及排序算法是如何依赖于此的。
发布于 2016-08-22 11:13:27
@sorted变量如果没有执行交换,您可以删除@sorted变量并直接返回,将循环更改为while true并添加return if swaps == 0而不是if swaps ... @sorted =...语句。
你也不需要一个类,你可以写一个顶级的函数或者把它放到一个模块中,一个类用来保存数据,一个函数来操作它,一个类包含一个静态函数是不合理的。
step方法您应该使用.step(2)方法,因为它比手动增量和修改体内的循环变量更显着,并且打破了我们已经知道for循环应该运行多少次的预期。
https://codereview.stackexchange.com/questions/139308
复制相似问题