Search code examples
pythonrecursionbubble-sort

Why is my recursive bubble sort not working?


When I run my recursive bubble sort on the list:

 ["4213", "4201", "4204", "4218", "4205", "Out"]

I get:

['4201', '4204', '4213', '4205', '4218', 'Out']

instead of the correct answer. Can anyone explain why?

def test_sort(list_to_sort):
    length = len(list_to_sort)
    if length == 0:
        return list_to_sort
    for i in range(0, length - 1):
        if list_to_sort[i] > list_to_sort[i + 1]:
            (list_to_sort[i], list_to_sort[i + 1]) = (list_to_sort[i + 1], list_to_sort[i])
    test_sort(list_to_sort[:length - 1])
    return list_to_sort

def main():
    testlist = ["4213", "4201", "4204", "4218", "4205", "Out"]
    print(test_sort(testlist))

Solution

  • You forgot to use the results of:

    test_sort(list_to_sort[:length - 1])
    

    You can change it to:

    list_to_sort[:length - 1] = test_sort(list_to_sort[:length - 1])
    

    Test Code:

    def test_sort(list_to_sort):
        length = len(list_to_sort)
        if length < 2:
            return list_to_sort
        for i in range(0, length - 1):
            if list_to_sort[i] > list_to_sort[i + 1]:
                list_to_sort[i:i + 2] = list_to_sort[i + 1], list_to_sort[i]
        list_to_sort[:length - 1] = test_sort(list_to_sort[:length - 1])
        return list_to_sort
    
    
    def main():
        testlist = ["4213", "4201", "4204", "4218", "4205", "Out"]
        print(test_sort(testlist))
    
    main()
    

    Results:

    ['4201', '4204', '4205', '4213', '4218', 'Out']