简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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