插入排序不正确排序数组

Atm*_*tma 2 python algorithm insertion-sort insertion-order

这是我的插入排序,与"算法简介"一书中的方式完全相同:

def insertion_sort():
    A = [5,2,4,6,1,3]
    for j in range(1, len(A)):
        print 'j:'+str(j)
        key = A[j]
        print 'key:'+str(key)
        i=j-1
        print 'i:'+str(i)
        while i > 0 and A[i] > key:
            A[i+1] = A[i]
            i=i-1
            print 'new i: '+str(i)
        print 'swapping value: '+str(A[i]) + ' with value: '+str(A[i+1])
        print ' '
        A[i+1] = key
    print A
Run Code Online (Sandbox Code Playgroud)

这打印:

[5, 1, 2, 3, 4, 6]
Run Code Online (Sandbox Code Playgroud)

如果让它们失灵,我做错了什么?

C.B*_*.B. 5

算法导论,他们总是假设数组索引1处开始,所以你开始你range()1,但是Python列表是从0开始的索引.这意味着你永远不会比较5,这是在A[0].注意5排序后的所有内容.

将你的for循环修改为 -

for j in range(0, len(A)):
Run Code Online (Sandbox Code Playgroud)

和你的条件

while i >= 0 and A[i] > key:
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩.