最佳答案
这里循环语句被认为被执行了一次,因为它在第一次迭代之前和最后一次迭代之后进行了比较。让我们考虑 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/