algorithm - 从clrs书上看,插入排序for循环为什么要迭代n次?

标签 algorithm sorting insertion-sort

enter image description here

为什么第一行从 2 开始迭代了 n 次?不应该是 n-1 吗? 还有为什么第 2 行和第 3 行是 n-1 而不是 n?

最佳答案

这里循环语句被认为被执行了一次,因为它在第一次迭代之前和最后一次迭代之后进行了比较。让我们考虑 A.length = 3。我们只有两次迭代,但是有三个比较:

j := 2
if j > A.length then exit the loop // first comparison, false
... first loop iteration goes

j := j + 1 // j = 3 now
if j > A.length then exit the loop // second comparison, false
... second loop iteration goes

j := j + 1 // j = 4 now
if j > A.length then exit the loop // third comparison, true

因此如您所见,我们必须比较三次,但循环体只执行了两次。第一次比较是必要的,因为如果 A.length = 1 我们根本不应该执行循环体。

关于algorithm - 从clrs书上看,插入排序for循环为什么要迭代n次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32576966/

相关文章:

java - 使用字符串进行插入排序

algorithm - 使 "Insertion sort"算法更高效 - Python 3.5.2

java - 去除插入排序中的重复项

c++ - 是否可以在没有临时存储的情况下进行就地合并?

php - 关联数组不存储 SQL 的第一个结果

algorithm - 在 O(1) 中高效地计算序列 2、2、4、2、4、6、2、4、6、8 ... 的第 i 个元素

r - 在 R 中对列进行数字排序

rest - Tornado 可以处理分页吗?

algorithm - 找到每个可能子集的第 k 个最小总和

algorithm - 有证据表明这个 big-o 陈述是错误的吗?