【问题标题】:Counting the number of comparisons and moves made during sorting计算排序期间的比较次数和移动次数
【发布时间】:2015-05-06 18:17:57
【问题描述】:

我正在进行插入排序,想知道是否正确计算了比较次数和移动次数。比较是比较两个值的次数,而移动是移动的元素数,因此数字之间的交换将是 2 次移动。

public static int[] InsertionSort(int[] a) {
    int j;
    for(int i = 1; i < a.length; i++) {
        int tmp = a[i];
        for(j = i; j > 0 && (tmp < a[j-1]); j--) {
            numCompares++;
            a[j] = a[j-1];
            numMoves++;
        }
        a[j] = tmp; 
        numMoves++;
    }
    return a;
}

【问题讨论】:

  • 很好,有问题吗?
  • numCompares++ 和 numMoves++ 是否放置在正确的位置以获得正确的计数?

标签: java sorting insertion-sort


【解决方案1】:

这里唯一的问题是在内部循环条件j &gt; 0 &amp;&amp; (tmp &lt; a[j-1]),实际比较tmp &lt; a[j-1]可能会导致错误,导致for循环中断,因此位于循环内部的numCompares++将被跳过。要精确计算比较,需要重新格式化:

for(j = i; j > 0; j--) {
    numCompares++; 
    if (tmp >= a[j - 1])
        break; 
    a[j] = a[j - 1];
    numMoves++;
}

【讨论】:

  • 或者你可以使用黑客j &gt; 0 &amp;&amp; numCompares++ &gt;= 0 &amp;&amp; tmp &lt; a[j-1]
  • @PeterLawrey 好吧,这更好:)
  • 感谢您的帮助。正是我需要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 2022-01-16
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多