【发布时间】:2015-09-15 02:53:55
【问题描述】:
【问题讨论】:
标签: algorithm sorting insertion-sort
【问题讨论】:
标签: algorithm sorting insertion-sort
这里的循环语句被认为是再执行一次,因为它在第一次迭代之前和最后一次迭代之后都进行了比较。让我们考虑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
因此,正如您所见,我们必须比较 3 次,但循环体只执行了两次。第一个比较是必要的,因为如果A.length = 1 我们根本不应该执行循环体。
【讨论】: