python中的插入排序不起作用

时间:2016-09-27 12:52:59

标签: python insertion-sort

我在python

中尝试了以下代码进行插入排序
a=[int(x) for x in input().split()]
for i in range(1,len(a)):
    temp=a[i]
    for k in range (i,1,-1):
        a[k]=a[k-1]
        if a[k]<temp:
            a[k]=temp
            break
print(a)

输入:6 4 3 2 5 8 1

输出:[6,4,4,4,4,5,8]

2 个答案:

答案 0 :(得分:0)

不起作用因为您的实施有问题 在尝试移动部分排序的列表时,您可以通过指定a[k] = a[k-1]来覆盖现有数字 - 但是之前的值是a[k]呢?

一个非常基本的解决方案(但由于定义了单个列表上的原始定义而未就位)可能看起来像这样。

inp = '1 4 6 3 1 6 3 5 8 1'

# 'a' is the input list
a = [int(x) for x in inp.split()]
# 'r' is the sorted list
r = []
# In the original descriptions, insertion sort operates
# on a single list while iterating over it. However, this
# may lead to major failurs, thus you better carry the
# sorted list in a separate variable if memory is not
# a limiting factor (which it can hardly be for lists that
# are typed in by the user).

for e in a:
    if not len(r):
        # The first item is the inialization
        r.append(e)
    else:
        # For each subsequent item, find the spot in 'r'
        # where it has to go.
        idx = 0
        while idx < len(r) and r[idx] < e: idx += 1
        # We are lazy and use insert() instead of manually
        # extending the list by 1 place and copying over
        # all subsequent items [idx:] to the right
        r.insert(idx, e)
print(r)

答案 1 :(得分:0)

我认为在迭代从索引1开始直到循环长度的序列后,我们需要使用while循环,因为我们需要对该序列进行多次迭代。

以下代码将完成这项工作。

import sys
def insertionsort(A):
    for i in range(1,len(A)):
        pos = A[i]
        j = i-1
        while j >= 0 and pos < A[j]:
            A[j+1] = A[j]
            j -= 1
        A[j+1] = pos


A = [55, 45, 2, 9, 75, 64]
insertionsort(A)
print(A)