Search code examples
pythonsortingbubble-sort

Python Bubble Sort Code Explanation


I am new to Python. How can we explain this code step by step. I couldn't understand some parts.

myList=[43,21,12,80,3,2,35]
end=len(myList)-1
while (end!=-1):
    swapped=-1
    for i in range(0,end):
        if myList[i]>myList[i+1]:
            temp=myList[i]
            myList[i]=myList[i+1]
            myList[i+1]=temp
            swapped=i
    end=swapped
print(myList)

Solution

  • Using while True would create an infinite loop if you forget to add code which will break the loop. In this case that break should only happen when swapped is still -1 at the end of the for-loop. Thus the following code:

    myList=[43,21,12,80,3,2,35]
    end=len(myList)-1
    while True:
        swapped=-1
        for i in range(0,end):
            if myList[i]>myList[i+1]:
                temp=myList[i]
                myList[i]=myList[i+1]
                myList[i+1]=temp
                swapped=i
        if swapped == -1:
            break
    print(myList)
    

    If you count the number of lines of this example and compare them with the original you'll see that the original is 1 line shorter. And checking against a value is in my opinion a better way-of-working than using while True: (or while False: for that matter).