【问题标题】:From the clrs book, why is the insertion sort for loop iterated n times?从 clrs 书中,为什么循环的插入排序迭代 n 次?
【发布时间】:2015-09-15 02:53:55
【问题描述】:

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

【问题讨论】:

    标签: algorithm sorting insertion-sort


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多