插入排序算法不起作用

时间:2015-04-16 05:21:38

标签: python algorithm sorting

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

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

3 个答案:

答案 0 :(得分:1)

第四行应该是:

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

而不是

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

答案 1 :(得分:0)

来自Wikipedia

for i ← 1 to length(A) - 1
    j ← i
    while j > 0 and A[j-1] > A[j]
        swap A[j] and A[j-1]
        j ← j - 1
    end while
end for

要翻译成Python:

def insertion_sort(A):
    for i in range(1, len(A)):
        j = i
        while j > 0 and A[j-1] > A[j]:
            swap(A, j, j-1)
            j = j - 1


def swap(A, f, t):
    A[t], A[f] = A[f], A[t]


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

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

答案 2 :(得分:0)

试试这个..

def insertion_sort(L):
for i in range(1, len(L)):
    val = L[i]
    x = i - 1
    while (x >= 0) and (L[x] > val):
        L[x + 1] = L[x]
        x = x - 1
    L[x + 1] = val
a = [5, 2, 6, 3, 1, 8]

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