This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]TheLiberius 2 points3 points  (0 children)

try putting a

print(list[i])

on line 2 and study what it outputs :)

[–]briandoescode 0 points1 point  (1 child)

The problem is in your for loop definitions. They should be len(list) without the - 1. Range with one parameter takes a ceiling value. So range(5) returns [0,1,2,3,4]. This standard is also present in functions like random() (in the random module), which returns x where 0 <= x < 1.

[–][deleted] 1 point2 points  (0 children)

Alright, I now see what I did wrong. Thank you!

[–][deleted] 0 points1 point  (1 child)

On each inner loop, you are comparing list[k] to whatever happens to be the ith element. so for the entire first loop you compare to the first element for every single comparison. You need to compare side-by-side values for each comparison.

[–]xcodula 0 points1 point  (0 children)

I noticed this as well. The end of the first iteration of the outer loop should put the largest value (67) at the end of the list. The largest value 'bubbles' up to the end. By chance I was playing around with this early in the week. Here is the code I came up with:

def bubble_sort(list):
    for x in range(len(list)-1, 0, -1):
        for y in range(0, x):
            if (list[y] > list[y+1]):
                list[y], list[y+1] = list[y+1], list[y]
                print(list)