【发布时间】:2015-08-25 16:17:22
【问题描述】:
这本书是这样计算插入排序的时间复杂度的:
令 T(n) 表示插入排序的复杂度,c 表示每次迭代中其他操作的总数,例如赋值和附加比较。因此,
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)我无法理解第一步。每个学期的这个“2”是从哪里来的。
请让解释尽可能简单(数学很难)。
算法:
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;
}
}
}
【问题讨论】:
-
提供算法;它可以帮助更好地解释
2。 -
@Colin 我已经提供了算法。
标签: java big-o insertion-sort