Search code examples
pythonrepeaterrepeatbubble-sort

Python - Bubble sort


Hi I reviewed other posts with bubble sort, but solution didn't work in my case: So algorithm works until I repeat few times while loop. But how can I do this without using input? Here is my code so you know what I mean:

x = [0, 0, 1, 3, 3, 2, 2, 1, 0, 4, 5]

h = None
flag = True

while flag == True:
    #flag = True
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
    #       flag = False
            h = x[i]
            x[i] = x[i + 1] 
            x[i + 1] = h
    print(x)        

    #input = raw_input('Satisfied? ')
    #if input == 'q':
    #   break

print(x)
'''
we can replace variable h, with:
x[i] , x[i+1] = x[i+1], x[i]
'''

Solution

  • You can make use of the sorted function in python, and change your code to be:

    while flag == True:
        for i in range(len(x) - 1):
            if x[i] > x[i + 1]:
                h = x[i]
                x[i] = x[i + 1] 
                x[i + 1] = h
    
        if sorted(x) == x: #x is already sorted
            flag = False
    

    Edit: Alternate solution which doesn't use python's built in sort function:

    while flag == True:
        flag = False
        for i in range(len(x) - 1):
            if x[i] > x[i + 1]:
                flag = True
                h = x[i]
                x[i] = x[i + 1] 
                x[i + 1] = h
    

    Hope I helped!