[英]Python - Merge Sort Recursive Algorithm
我試圖為遞歸合並排序算法實現這個偽代碼:
**procedure** *mergesort*(L = a1, a2,…,an )
**if** n > 1 **then**
m := ⌊n/2⌋
L1 := a1, a2,…,am
L2 := am+1, am+2,…,an
L := merge(mergesort(L1), mergesort(L2 ))
{L is now sorted into elements in increasing order}
**procedure** *merge*(L1, L2 :sorted lists)
L := empty list
**while** L1 and L2 are both nonempty
remove smaller of first elements of L1 and L2 from its list;
put at the right end of L
**if** this removal makes one list empty
**then** remove all elements from the other list and append them to L
return L {L is the merged list with the elements in increasing order}
它的目的是在python上編寫它,到目前為止我編寫了所有它但它運行不正常,每次我運行它打印:函數合並在0x0000000002024730。 這是python代碼:
#Recursive Merge Sort
import math
ent = [10000, 967, 87, 91, 117, 819, 403, 597, 1201, 12090]
def merge(L1, L2):
while len(L1) and len(L2) != 0:
L.append(L1[0])
L1.remove(L1[0])
L.append(L2[0])
L2.remove(L2[0])
if len(L1) == 0:
L.append(L2)
elif len(L2) == 0:
L.append(L1)
return L
def mergesort(ent):
if len(ent)>1:
m=math.floor(len(ent)/2)
L1 = []
L2 = []
L1=L1+ent[:m]
L2=L2+ent[m+1:len(ent)]
L=merge(mergesort(L1),mergesort(L2))
print(merge)
我對這些函數是如何以遞歸方式共同工作有一些疑問,這就是為什么我認為我無法解決和編碼正確的原因。 任何幫助或建議?
您沒有執行merge
,而是打印函數本身 。 做這個:
print(merge())
但是,你的邏輯有點亂,你甚至沒有遞歸功能。
看看這個問題
另外,我認為你需要的是調用mergesort:
def mergesort(ent):
if len(ent)>1:
m=math.floor(len(ent)/2)
L1 = ent[:m]
L2 = ent[m+1:len(ent)]
L=merge(mergesort(L1),mergesort(L2))
return L
並執行它:
print(mergesort(ent))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.