【问题标题】:Insertion sort in best case最佳情况下的插入排序
【发布时间】:2018-03-20 03:48:18
【问题描述】:

参考 Robert 和 KevinAlgorithm - Fourth Edition,我很难按照以下代码理解插入排序的最佳情况复杂性:

    public class Insertion
{
    public static void sort(Comparable[] a)
    { // Sort a[] into increasing order.
        int N = a.length;
        for (int i = 1; i < N; i++)
            { // Insert a[i] among a[i-1], a[i-2], a[i-3]... ..
                for (int j = i; j > 0 && less(a[j], a[j-1]); j--)
                    exch(a, j, j-1);
        }
    }
// See page 245 for less(), exch(), isSorted(), and main().
}

书中说,在最好的情况下(排序数组),交换次数为 0,比较次数为 N-1。虽然我理解交换为 0,但我很难在最佳情况下,比较次数如何为 N-1?

【问题讨论】:

    标签: algorithm insertion-sort


    【解决方案1】:

    如果数组已经排序,那么在您提供的插入排序的具体实现中,每个元素只会与其立即前身进行比较。由于它不小于前一个,因此内部的for-loop 立即中止,无需任何进一步的比较或交换。

    请注意,插入排序的其他实现不一定具有该属性。

    【讨论】:

      【解决方案2】:

      具体实现源码为:

          public class Insertion
      {
          public static void sort(Comparable[] a)
          { // Sort a[] into increasing order.
              int N = a.length;
              bool exc = false;
              for (int i = 1; i < N; i++)
                  { // Insert a[i] among a[i-1], a[i-2], a[i-3]... ..
                      for (int j = i; j > 0 && less(a[j], a[j-1]); j--) {
                          exch(a, j, j-1);
                          exc = true;
                      }
                   if (!exc)
                       break;
              }
          }
      // See page 245 for less(), exch(), isSorted(), and main().
      }
      

      【讨论】:

        【解决方案3】:

        在最佳情况下,比较次数如何为 N-1?

        最好的情况发生在你有一个已经排序的数组时。比较的次数是n-1,因为比较是从第二个元素开始直到最后一个元素。

        这也可以从您给定的代码中观察到:

        for (int i = 1; i < N; i++)    //int i=1 (start comparing from 2nd element)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多