插入排序递归不拾取最后一个元素 [5,4,3,2,1,0] 排序后 [1,2,3,4,5,0] 最后一个元素未排序

Insertion Sort Recursion not picking up last element [5,4,3,2,1,0] After sortin [1,2,3,4,5,0] Where last element not sorted

一直卡在自己写递归插入排序的问题中间。该程序运行良好,但没有选择最后一个元素进行排序 [5,4,3,2,1,0]。执行后:[1,2,3,4,5,0]

from array import *
mylist = array('i',[5,4,3,2,1,0])

def insertionsort(mylist):
    if len(mylist)>1:
        mylist = mylist[:len(mylist)-1]
        insertionsort(mylist)
        i = len(mylist)-1
        key = mylist[i]
        j = i-1
        
        while j>=0 and key<mylist[j]:
            mylist[j+1] = mylist[j]
            j = j-1
        mylist[j+1] = key

insertionsort(mylist)
print(mylist)

这应该有效

from array import * 

mylist=array('i',[5,4,3,2,1,0])

def insertionsort(mylist, l): 
    if l>1: 
        insertionsort(mylist, l-1) 
    i=l-1
    key=mylist[i] 
    j=i-1

    while j>=0 and key<mylist[j]:
        mylist[j+1]=mylist[j]
        j=j-1
    mylist[j+1]=key

insertionsort(mylist, len(mylist)) 
print(mylist)

试试这个:

mylist = [5,4,3,2,1,0]

def insertionsort(mylist,n):
    if n<=1:
        return
    insertionsort(mylist,n-1)
    key = mylist[n-1]
    j = n-2
     
    while (j>=0 and key < mylist[j]):
        mylist[j+1] = mylist[j]
        j = j-1
 
    mylist[j+1]=key


insertionsort(mylist, len(mylist))
print(mylist)

输出:

[0, 1, 2, 3, 4, 5]