首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >红宝石气泡排序算法

红宝石气泡排序算法
EN

Code Review用户
提问于 2016-08-21 21:41:23
回答 2查看 388关注 0票数 3

我只是在寻求对我的Ruby实现泡沫排序算法的建设性批评。

代码语言:javascript
复制
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
EN

回答 2

Code Review用户

回答已采纳

发布于 2016-08-21 22:54:51

虽然你应该评论你的工作,但你的一些评论似乎是没有必要的。让我们看一些行,看看为什么:

代码语言:javascript
复制
# parse the list until it is sorted
until @sorted == true

这句话似乎多余。您的代码行until @sorted == true读得很清楚,我可以理解您想要一直做一些事情,直到列表被排序。

代码语言:javascript
复制
# 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是众所周知的,所以您可能甚至不需要对此发表评论。

代码语言:javascript
复制
# increase the number of swaps performed in this run by 1
swaps += 1

再说一遍为什么?我可以阅读代码,很明显,您正在增加swaps的数量。我会省略的。

代码语言:javascript
复制
# compare the next 2 elements
i += 1

基于if语句,我会知道这是i的目的。我会省略它,但它确实解释了为什么要增加i,所以这里有一些灰色区域。

最后写一些好的评论,让我们分析它们为什么是好的:

代码语言:javascript
复制
# 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以及排序算法是如何依赖于此的。

票数 2
EN

Code Review用户

发布于 2016-08-22 11:13:27

不需要@sorted变量

如果没有执行交换,您可以删除@sorted变量并直接返回,将循环更改为while true并添加return if swaps == 0而不是if swaps ... @sorted =...语句。

不需要类

你也不需要一个类,你可以写一个顶级的函数或者把它放到一个模块中,一个类用来保存数据,一个函数来操作它,一个类包含一个静态函数是不合理的。

Ruby step方法

您应该使用.step(2)方法,因为它比手动增量和修改体内的循环变量更显着,并且打破了我们已经知道for循环应该运行多少次的预期。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/139308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档