[英]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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.