Search code examples
pythonpython-3.xrecursionpseudocode

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


I've got a pseudocode for making a recursive version of a bubble sort function. I've been trying to convert it into a working function in python but am having a hard time doing it. Here's the pseudocode:

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   

Here's the code which I've made with the help of the pseudocode

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

When I use a list like [14,26,83,17,87] and use the bsort([14,26,83,17,87]) function it gives an output [14,17]. Shouldn't the output for this bubble sort function be [14, 17, 26, 83, 87]. I don't understand what I'm missing. Any help would be appreciated.


Solution

  • I don't understand why you have complicated this so much but this should work ;)

    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
    

    The mistake was in return after if L[0] <= T[0]: condition because you return 2 list heads instead of head and a tail.