[英]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.