从clrs书中,为什么循环的插入排序迭代了n次?

时间:2015-09-15 02:53:56

标签: algorithm sorting insertion-sort

enter image description here

为什么第一行迭代n次,从2开始?难道不是n-1吗? 另外,为什么第2行和第3行是n-1而不是n?

1 个答案:

答案 0 :(得分:3)

这里循环语句被认为再次执行,因为它在第一次迭代之前和最后一次迭代之后进行了比较。我们考虑一下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我们根本不应该执行循环体。

相关问题