def insertion_sort(L):
    for i in range(1,len(L)):
        x = i
        while x > 0 and L[x-1] >= L[x]:
            x -= 1
        value = L[i]
        del L[i]
        L.insert(x,value)

a = [5,2,6,3,1,8]

print "Before: ", a
insertion_sort(a)
print "After:  ", a

由于某些原因,列表没有正确排序我在这里找不到错误。

最佳答案

第四行应该是:

while x > 0 and L[x-1] >= L[i]:

而不是
while x > 0 and L[x-1] >= L[x]:

关于python - 插入排序算法不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29665930/

10-12 07:38
查看更多