python 中的插入排序不起作用
insertion sort in python not working
我在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]
它不起作用因为你的实现有问题。
当尝试移动部分排序的列表时,您通过分配 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 开始迭代序列直到循环长度后,我们需要使用 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)
我在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]
它不起作用因为你的实现有问题。
当尝试移动部分排序的列表时,您通过分配 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 开始迭代序列直到循环长度后,我们需要使用 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)