【问题标题】:Why do i need a new variable in the while loop of this implementation of Insertionsort?为什么我在 Insertionsort 的这个实现的 while 循环中需要一个新变量?
【发布时间】:2020-07-27 09:58:48
【问题描述】:

我有一个插入排序算法的实现,在讲座中,在 while 循环之前有一个新的实例变量。

def swap(l, i, j):
    temp = l[i]
    l[i] = l[j]
    l[j] = temp


def ins_sort(l):
    for i in range(len(l)):
        j = i
        while j > 0 and l[j - 1] > l[j]:
            swap(l, j - 1, j)
            j = j - 1


    return l

在我的测试中,算法在没有它的情况下也可以工作,我不明白为什么如果没有必要我需要编写额外的代码行。

def swap(l, i, j):
    temp = l[i]
    l[i] = l[j]
    l[j] = temp


def ins_sort(l):
    for i in range(len(l)):
        while i > 0 and l[i - 1] > l[i]:
            swap(l, i - 1, i)
            i = i - 1


    return l

【问题讨论】:

  • 临时值也不需要swap 函数。 l[i], l[j] = l[j], l[i] 也应该这样做
  • 看来作者不懂Python。

标签: python insertion-sort


【解决方案1】:

看起来原始代码是从 c/c++ 实现的翻译,其中在循环内修改 i 将是持久的并影响循环本身。但是,由于在 python 中,每次迭代都会重置我,第二个代码也将起作用。 简而言之,我认为这行对于 python 实现来说是不必要的。

参考:Scope of python variable in for loop

【讨论】:

  • 感谢您的回答和参考并为我清理
【解决方案2】:

您也可以尝试以下程序进行插入排序,其中不需要使用额外变量:

l=[4,3,1,2]
for i in range(1,len(l)): 
      key=l[i]  
      for j in range(i-1,-1,-1):
          if l[j]>key:
              l[j+1]=l[j]
          else:
              j=j+1
              break

      l[j]=key

print(l)

【讨论】:

    猜你喜欢
    • 2014-06-11
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多