【问题标题】:Cannot understand how my book is counting algorithm steps无法理解我的书是如何计算算法步骤的
【发布时间】:2014-04-03 05:16:36
【问题描述】:

在这个例子中,我的书向我展示了如何计算冒泡排序算法中的步数。代码中的每条注释都解释了添加到 steps 的金额的原因。

代码:

public void bubbleSort(ArrayList <Comparable> list){
   steps = 0;
   for (int outer = 0; outer < list.size() - 1; outer++){
     for (int inner = 0; inner < list.size()-outer-1; inner++){
         steps += 3;//count one compare and 2 gets
         if (list.get(inner).compareTo(list.get(inner + 1)) > 0){
            steps += 4;//count 2 gets and 2 sets
            Comparable temp = list.get(inner);
            list.set(inner,list.get(inner + 1));
            list.set(inner + 1,temp);
         }
     }
   }
 }

查看steps += 4; 时,我明白他们为什么要添加4:仅仅是因为有2 个get 语句和2 个set 语句。但是在这一步steps += 3;//count one compare and 2 gets 我不明白为什么要添加 3。在if 语句之前的代码中哪里有比较语句?此外,if 语句之前的“2​​ 个获取”在哪里?也许我误解了他们计算步数的方式,但这实际上是我提供的所有书。

【问题讨论】:

  • 也许 list.size()x2 是你的 2 次获得,比较是内部
  • 好吧,那么外部 for 中的 list.size() 也会被计算在内。

标签: java sorting


【解决方案1】:

if 语句本身有两个 get 和一个 compare:

if (list.get(inner).compareTo(list.get(inner + 1)) > 0)

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 2014-12-14
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 2016-08-27
    • 1970-01-01
    相关资源
    最近更新 更多