python中的插入排序不起作用
我在python中尝试了以下插入排序代码python中的插入排序不起作用,python,insertion-sort,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) a=[input().split()中x的int(x)]
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)
a=[input().split()中x的int(x)]
对于范围(1,len(a))中的i:
温度=a[i]
对于范围(i,1,-1)内的k:
a[k]=a[k-1]
如果[k]由于您的实现有故障而无法工作。
当尝试移动部分排序的列表时,您可以通过分配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)
inp='1 4 6 3 1 6 3 5 8 1'
#“a”是输入列表
a=[inp.split()中x的int(x)]
#“r”是已排序的列表
r=[]
#在原始描述中,插入排序操作
#在单个列表上进行迭代时。但是,
#可能会导致重大故障,因此您最好随身携带
#如果内存不可用,则在单独变量中排序列表
#限制因素(对于那些
#由用户输入)。
对于a中的e:
如果不是len(r):
#第一项是初始化
r、 附加(e)
其他:
#对于每个后续项目,请在“r”中找到该点
#它必须去哪里。
idx=0
而idx
我认为在从索引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)
导入系统
def insertionsort(A):
对于范围(1,len(A))中的i:
pos=A[i]
j=i-1
当j>=0且pos
根据wiki页面欢迎来到StackOverflow!我猜你的问题被否决了,因为你的问题没有显示出太多的研究成果。这是一个非常常见的问题,快速的谷歌搜索应该会给你很多结果。请阅读。