【问题标题】:Insertion sort doesn't work插入排序不起作用
【发布时间】:2014-12-13 20:40:48
【问题描述】:

我写了这个插入排序,但由于某种原因它没有返回任何东西,我不知道为什么。有人可以看看这个吗?

def insertionSort(lis):
    for i in range (1, len(lis)):
        j = i - 1
        value = lis[i]
        while j >= 0:
            if value < lis[j]: #have to be value because the number has to remain the same
                lis[j+1] = lis[j]
                j-= 1
            else:
                lis[j+1] = value
    return lis

【问题讨论】:

  • 这是您使用的实际缩进吗?
  • 你能修正你的缩进,让它看起来和你的代码完全一样吗?此代码不会运行。
  • 对不起,不是,只是修复了缩进
  • “不返回任何东西”是什么意思?空列表,永不返回,返回值为 None 等?
  • 无限循环。如果您的 if 子句没有触发,j 保持不变。

标签: python sorting insertion-sort


【解决方案1】:

你有一个无限循环。 在这段代码中:

while j >= 0:
    if value < lis[j]: #have to be value because the number has to remain the same
        lis[j+1] = lis[j]
        j-= 1
    else:
        lis[j+1] = value

一旦达到value &lt; lis[j] 为假的点,j 就不会递减,并且您的while 循环将永远不会退出。

如果你愿意,我可以为你编写一个正确的插入排序,但我认为这会破坏你尝试自己做的意义。

【讨论】:

    【解决方案2】:

    请看一下这个示例代码,它可能对你有帮助

    def insertionSort(alist):
    
       for index in range(1,len(alist)):
    
         currentvalue = alist[index]
    
         position = index
    
      while position>0 and alist[position-1]>currentvalue:
    
           alist[position]=alist[position-1]
    
           position = position-1
    
      alist[position]=currentvalue
    
    
     alist = [54,26,93,17,77,31,44,55,20]
    
     insertionSort(alist)
    
     print(alist)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多