1.11M Members

Python Bubble Sort Code

 
1
 

Hello everyone;
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)
 
1
 

You can insert a print statement for testing the progress, and see how the higher values bubble to the end and lower values bubble to the start of the list:

myList=[43,21,12,80,3,2,35]
print(myList)
print('-'*30)

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

            print(myList)  # test print to follow progress of sort

            swapped = i
    end = swapped

print('-'*30)
print(myList)

'''
[43, 21, 12, 80, 3, 2, 35]
------------------------------
[21, 43, 12, 80, 3, 2, 35]
[21, 12, 43, 80, 3, 2, 35]
[21, 12, 43, 3, 80, 2, 35]
[21, 12, 43, 3, 2, 80, 35]
[21, 12, 43, 3, 2, 35, 80]
[12, 21, 43, 3, 2, 35, 80]
[12, 21, 3, 43, 2, 35, 80]
[12, 21, 3, 2, 43, 35, 80]
[12, 21, 3, 2, 35, 43, 80]
[12, 3, 21, 2, 35, 43, 80]
[12, 3, 2, 21, 35, 43, 80]
[3, 12, 2, 21, 35, 43, 80]
[3, 2, 12, 21, 35, 43, 80]
[2, 3, 12, 21, 35, 43, 80]
------------------------------
[2, 3, 12, 21, 35, 43, 80]
'''

Also the C type swap

        temp = myList[i]
        myList[i] = myList[i+1]
        myList[i+1]= temp

can be replaced with a Python tuple swap

myList[i+1], myList[i] = myList[i], myList[i+1]

 
0
 

Let us know if this helped.

Question Answered as of 1 Year Ago by vegaseat and sneekula
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: