尝试从伪代码制作泡泡排序函数的递归版本

问题描述 投票:0回答:1

我有一个伪代码用于制作冒泡排序函数的递归版本。我一直在尝试将它转换为python中的一个工作函数,但我很难做到这一点。这是伪代码:

def bsort(L):
   if the length of L is less than or equal to 1:
        return L
   else:
        bubble sort the tail of L (all elements of L except the first) to get a sorted list called T
        if the head (first element) of L is less than or equal to  the head T:
              return  a list formed by joining the ehad of L with T
         else:
              combine the head of L and the tail of T to get a list called P
              bubble sort P to get a list called Q
              return a list formed by joining the head of T with Q   

这是我在伪代码的帮助下创建的代码

def bsort(L):
    if len(L)<=1:
        return L
    else:
        T= bsort(L[1:])
        if L[0]<=T[0]:
            return (L[0] if type(L[0]) is list else [L[0]]) + (T[0] if type(T[0]) is list else [T[0]])
        else:
            P= (L[0] if type(L[0]) is list else [L[0]]) + (T[1:] if type(T[1:]) is list else [T[1:]])
            Q= bsort(P)
            return (T[0] if type(T[0]) is list else [T[0]]) + (Q if type(Q) is list else [Q])

当我使用像[14,26,83,17,87]这样的列表并使用bsort([14,26,83,17,87])函数时,它会给出输出[14,17]。这个冒泡排序函数的输出不应该是[14, 17, 26, 83, 87]。我不明白我错过了什么。任何帮助,将不胜感激。

python python-3.x recursion pseudocode
1个回答
0
投票

我不明白为什么你这么复杂,但这应该工作;)

def bsort(L):
if len(L) <= 1:
    return L
else:
    T = bsort(L[1:])
    if L[0] <= T[0]:
        return [L[0]] + T
    else:
        P = [L[0]] + T[1:]
        Q = bsort(P)
        return [T[0]] + Q

如果L [0] <= T [0]:条件因为你返回2个列表头而不是头部和尾部,则会出现错误。

© www.soinside.com 2019 - 2024. All rights reserved.