【问题标题】:insertion sort in python not workingpython中的插入排序不起作用
【发布时间】:2016-09-27 12:52:58
【问题描述】:
我已经尝试了以下代码在 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]
【问题讨论】:
-
-
欢迎来到 StackOverflow!我想您的问题已被否决,因为您的问题没有显示出大量的研究工作。这是一个非常常见的问题,快速的谷歌搜索应该会给你很多结果。请阅读How to ask。
标签:
python
insertion-sort
【解决方案1】:
它不起作用,因为你的实现有问题。
当尝试移动部分排序的列表时,您通过分配 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)
【解决方案2】:
我认为在从索引 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)