We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,397 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Python Bubble Sort Code

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)
3
Contributors
2
Replies
11 Hours
Discussion Span
5 Months Ago
Last Updated
6
Views
Question
Answered
flopoe
Newbie Poster
1 post since Nov 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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]

sneekula
Nearly a Posting Maven
2,483 posts since Oct 2006
Reputation Points: 1,000
Solved Threads: 231
Skill Endorsements: 2

Let us know if this helped.

vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 37
Question Answered as of 5 Months Ago by sneekula and vegaseat

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.2995 seconds using 2.71MB