Python - 归并排序递归算法

标签 python function recursion pseudocode

我试图为递归合并排序算法实现这个伪代码:

**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())

但是,你的逻辑有点乱,你那里甚至没有递归函数。

看看这个question

此外,我认为您需要调用合并排序:

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))

关于Python - 归并排序递归算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19992992/

相关文章:

python - pip install census for census.gov API

自执行 block 中的 Javascript 函数无法访问。为什么?

c++ - 在表达式中使用 pow 函数

javascript - 如何递归地查找字符串中的一组字符?

Prolog 中的递归 - 寻找城市之间的路径

python - 局部变量和全局变量的区别

python - python中的Redis,如何关闭连接?

list - F#:递归函数:连接 2 个具有公共(public)元素的列表

python - 在 C 和 Python 中循环

c++ - 没有非空函数的返回语句是否是未定义的行为,其中控制永远不会结束?