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

Trying to make a recursive version of bubble sort function from a pseudocode

我有一个伪代码,用于制作冒泡排序函数的递归版本。我一直在尝试将它转换为 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]。我不明白我错过了什么。任何帮助将不胜感激。

我不明白你为什么把它弄得这么复杂,但这应该有用 ;)

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

错误出现在 return if L[0] <= T[0]: 条件之后,因为你 return 2 列出了头部而不是头部和尾部。