简体   繁体   English

插入排序无效

[英]Insertion sort doesn't work

I wrote this insertion sort, but for some reason it doesn't return anything, and I can't figure out why. 我写了这种插入排序,但是由于某种原因,它不返回任何内容,我也不知道为什么。 Could someone take a look at this? 有人可以看看吗?

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

You have an infinite loop. 您有一个无限循环。 In this code: 在此代码中:

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

as soon as you reach a point where value < lis[j] is false, j is not decremented and your while loop will never exit. 一旦达到value < lis[j]为false的点, j就不会递减,并且while循环将永远不会退出。

I can write a correct insertion sort for you if you want, but I think that would defeat the point of you trying to do it yourself. 如果您愿意,我可以为您写一个正确的插入排序,但是我认为那会挫败您自己尝试插入的目的。

Please take a look at this sample code ,It maybe helpful for you 请查看此示例代码,这可能对您有帮助

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM