Ryan Postell
Ryan Postell

Reputation: 15

bubblesort function in python 3

I'm trying to understand how bubbleset works. I know there are multiple threads about this here but they are all different versions of the function and don't do a good job explaining to a newbie. I found this succinct code for a bubblesort on youtube:

def bubblesort(mylist):
for i in range(0, len(mylist) - 1):
    for j in range(0, len(mylist) - 1 - i):
        if mylist[j] > mylist[j+1]:
            mylist[j], mylist[j+1] = mylist[j+1], mylist[j]
return mylist

can someone explain to me the purpose of line 3 where it says len(mylist) - 1 - i? Why are we subtracting i? what does mylist do?

I'm a beginner programmer, just trying to get a better understanding on how these loops are working.

Upvotes: 0

Views: 333

Answers (1)

Anthony Pham
Anthony Pham

Reputation: 3106

This is because after each iteration, the last number is sorted. To elaborate, let's look at this list:

[0, 2, 5, 7, 3, 1]

After the first sort, the largest number will be sorted. After the second sort, the second-largest number has been sorted. Or basically, the number at the index len(myList ) - 1 - iteration will be sorted already and will be at the correct position. After the first sort, the largest number is in place. The largest number's index is now at len(myList) - 1. Then the second largest number will be placed correctly, this iteration goes from 0 to 1 so the second largest number's index is now len(myList) - 1 - iteration or len(myList) - 1 - 1 which is right before the largest number.

Upvotes: 2

Related Questions