Search code examples
pythonalgorithmbubble-sort

Issue with bubble sorting


SO I decided to create a bubble algorithm in Python. The thing is that it works for some numbers, but it doesn't work for others. Can anyone help:

def sort(number):
    to_sort = list(str(number))
    sorted_list = sorted(to_sort)
    print(sorted_list)
    i = 0
    while True:
        if to_sort == sorted_list:
            print(f"Sorted {number} to {''.join(to_sort)}" )
            break
        first_index = to_sort[i]
        try:
            second_index = to_sort[i+1]
        except IndexError:
            i = 0
        if first_index < second_index:
            i += 1
            print(to_sort)
            continue
        elif first_index > second_index:
            print(f"switching {to_sort[i+1]} to {first_index}")
            to_sort[i+1] = first_index
            print(to_sort)
            print(f"Switching {to_sort[i]} to {second_index}")
            to_sort[i] = second_index
            print(to_sort)
            i += 1
            continue

sort(49304)

It works for 51428 but not 49304. Anyone know why?


Solution

  • The fatal flaw is in your loop reset (to 0), combined with your disconnected swapping logic.

        first_index = to_sort[i]
        try:
            second_index = to_sort[i+1]
        except IndexError:
            i = 0
        ...
        elif first_index > second_index:
            ...
            to_sort[i] = second_index
    

    In the case of running off the end of the list, second_index now has the wrong value: it's the previous value, since you never reset it after looping i back to 0.

    (1) Fix your immediate problem by inserting that reset:

        except IndexError:
            i = 0
            second_index = to_sort[0]
    

    (2) Research existing bubble sorts. Among other things, make your exchange simpler.

        to_sort[i], to_sort[i+1] = to_sort[i+1], to_sort[i]
    

    Control i so that it doesn't go out of bounds. Note that you don't have to really worry about swapping the last element with the first: a bubble sort doesn't skip ends like that.