简体   繁体   English

查找插入排序的大时间复杂度

[英]Finding big-o time complexity of insertion sort

This is how the book calculates Insertions sort's time complexity: 这是本书计算插入排序时间复杂度的方法:

Let T(n) denote the complexity for insertion sort and c denote the total number of other operations such as assignments and additional comparisons in each iteration. 令T(n)表示插入排序的复杂度,而c表示其他操作的总数,例如每次迭代中的赋值和其他比较。 Thus, 从而,

T(n) = (2 + c) + (2 * 2 + c) + . . . + (2 * (n - 1) + c)   --->  (1)

     = 2(1 + 2 + . . . + n - 1) + c(n - 1)   --->  (2)

     = 2((n - 1)n/2) + cn - c = n2 - n + cn - c   --->  (3)

     = O(n2)   --->  (4)

I can't understand the first step. 我不明白第一步。 Where is this '2' in every term coming from. 每个术语中的“ 2”来自哪里。

Please keep the explanation as simple as possible (Mathematics gives a hard time). 请保持解释尽可能简单(数学很难)。

Algorithm: 算法:

public class InsertionSort {
/** The method for sorting the numbers */
  public static void insertionSort(double[] list) {
    for (int i = 1; i < list.length; i++) {
    /** insert list[i] into a sorted sublist list[0..i-1] so that
       list[0..i] is sorted. */
       double currentElement = list[i];
       int k;
       for (k = i - 1; k >= 0 && list[k] > currentElement; k--) {
         list[k + 1] = list[k];
       }

       // Insert the current element into list[k+1]
       list[k + 1] = currentElement;
    }
  }
}

The 2 is a possible definition. 2是可能的定义。 The processing of the alghorithm is divided in something like steps. 算法的处理分为几个步骤。 You could say he uses one step to calculate the comparison in for loop and one step to assign the value. 您可以说他使用了一步来计算for循环中的比较,然后使用一步来分配值。

Moreover you see that you have a nested loop. 此外,您看到您有一个嵌套循环。 So for better reading I name the outter loop i-loop and the inner loop j_i-loop. 因此,为了更好地阅读,我将外部循环命名为i循环,将内部循环命名为j_i循环。 The time to process the j_i-loop is 2 * (i -1) . 处理j_i循环的时间为2 * (i -1) The time to process the i-loop is the time to process (j_1-loop +c)+(j_2-loop +c)+...+(j_n-loop+c) . 处理i循环的时间就是处理(j_1-loop +c)+(j_2-loop +c)+...+(j_n-loop+c)

Now you get the term in first line. 现在,您在第一行得到了该术语。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM