[英]Error with Insertion Sort Python
我正在嘗試使用python實現插入排序。 這是我的代碼:
def insertionSort(lst):
lstSorted = [lst[0]]
for i in range(1,len(lst)):
index = len(lstSorted)-1
while index >= 0:
if lst[i] > lstSorted[index]:
lstSorted.insert((index+1),lst[i])
else:
lstSorted.insert(index,lst[i])
index -= 1
return lstSorted
def main():
lst = [100,10,10000,1000,1000000,10000]
sortedLst = insertionSort(lst)
print(sortedLst)
main()
這是輸出:
[10, 10000, 10000, 1000000, 1000, 10000, 10000, 1000000, 1000, 10000, 10000, 1000000, 10000, 10000, 10000, 1000000, 100, 10000, 10000, 1000000, 1000, 10000, 10000, 1000000, 1000, 10000, 10000, 1000000, 10000, 10000, 10000, 1000000]
我意識到我的“ index- = 1”存在錯誤,但是我不確定如何解決。 當到達以下位置時,這是一個問題:
10, 100, 10000
while循環永遠不會中斷,因為索引為0,因此while循環再次運行,因此變為:
10, 10000, 100, 10000
我該如何解決?
發生的事情是,每次執行if
和if
傳遞時,它將在其前面插入元素。 嘗試這個,
def insertionSort(lst):
for i in range(1,len(lst)):
j = i
while j > 0:
if lst[j-1] > lst[j]:
t=lst[j]
lst[j]=lst[j-1]
lst[j-1]=t
j-= 1
return lst
def main():
lst = [100,10,10000,1000,1000000,10000]
sortedLst = insertionSort(lst)
print(sortedLst)
main()
您正在做的是如果lst中的元素大於lstSorted中的元素,則在lstSorted元素之后插入lst元素,但是如果較小,則將其添加到lstSorted中的元素之前,然后遞減索引並再次進行比較。 因此,如果列表為[5,4,3]
第一個循環lstSorted變為[4,5]
但是第二個循環則變為[3,4,3,5]
您需要做的是選擇適當的位置放入lst[i]
,然后將其插入。
因此,如果您想要單獨的列表,則可以將腳本修改為
def insertionSort(lst):
lstSorted = [lst[0]]
for i in range(1,len(lst)):
index = i-1
while index >= 0:
if lst[i] > lstSorted[index]:
lstSorted.insert((index+1),lst[i])
break
index -= 1
if index==-1:
lstSorted.insert(0,lst[i])
return lstSorted
def main():
lst = [100,10,10000,1000,1000000,10000]
sortedLst = insertionSort(lst)
print(sortedLst)
main()
您遇到的問題是,您正在重復將相同的值插入while
循環中的排序列表中。 您只想插入一次(每個for
循環周期),因此您需要稍微更改一下邏輯。
最簡單的更改是在第一個insert
調用之后添加一個break
,然后將else
塊從if
移到while
循環(並將插入索引更改為0
)。 這使用了Python的一個相對不尋常的功能,即循環可以具有else
塊,這些塊僅在循環運行完成而沒有命中break
語句時才運行。
def insertionSort(lst):
lstSorted = [lst[0]]
for i in range(1,len(lst)):
index = len(lstSorted)-1
while index >= 0:
if lst[i] > lstSorted[index]:
lstSorted.insert(index + 1, lst[i])
break # stop the while loop after inserting
index -= 1
else: # if we reached index -1 without breaking, insert at the start
lstSorted.insert(0, lst[i])
return lstSorted
您可能會注意到,雖然索引0
處的insert
實際上仍然是index+1
,就像另一個插入調用一樣,所以實際上我們可以將兩種情況組合成一個。 我認為這要優雅得多:
def insertionSort(lst):
lstSorted = [lst[0]]
for i in range(1,len(lst)):
index = len(lstSorted)-1
while True: # loop until a break is reached
if index < 0 or lst[i] > lstSorted[index]: # combine both insert cases
lstSorted.insert(index + 1, lst[i])
break
return lstSorted
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.