Search code examples
pythonsortingbubble-sort

Issue with Bubble Sort, First Value Not Sorted Properly


I have setup a bubble sort for a simple array but have one weird issue I don't understand where the first value is not sorted properly in the output and for some reason zeros are not sorting properly.

Also, the assignment only calls for sorting a list of integers, but when I insert string values into the list it creates an error because the > operator can only compare integers. For curiosity sake, is there a simple fix for this or would that require a more robust method? Thanks!

I can "fix" the sorting issue for the first number by adding another for loop within the function but outside the while loop, but this seems like an inefficient patch to cover some sort of logical error and still leaves the issue with zeros, can someone explain why this is happening?

Y=[3, 2, 1, 9, 3, 8, 3, 0, 7]

def s_list( C ):
    length = len(C) - 1
    ordered = False   
    while not ordered:
        ordered = True
        for i in range(length):
            if int(C[i]) > int(C[i+1]):
                sorted = False
                C[i], C[i+1] = C[i+1], C[i]

    return C

Expectation: [0, 1, 2, 3, 3, 3, 7, 8, 9] Reality: [2, 1, 3, 3, 8, 3, 0, 7, 9]


Solution

  • You set ordered to False initially, and then to True at the start of the while loop. This is fine, but then in the if-statement you set sorted to 'False'. These are two separate variables. Change sorted to ordered and it should work.