Skip to content

Instantly share code, notes, and snippets.

@daGrevis
Created February 15, 2012 16:16
Show Gist options
  • Select an option

  • Save daGrevis/1836991 to your computer and use it in GitHub Desktop.

Select an option

Save daGrevis/1836991 to your computer and use it in GitHub Desktop.
Bubble sort in Python
def bubble(list):
length = len(list) - 1
sorted = False
while not sorted:
sorted = True
for i in range(length):
if list[i] > list[i + 1]:
sorted = False
list[i], list[i + 1] = list[i + 1], list[i]
return list
print bubble([3, 6, 2, 5, 1, 6, 2])
@ArtyomKozyrev8

Copy link
Copy Markdown

Hello, it seems there is mistake in the code:
def bubble(list_):
length_ = len(list_) - 1
sorted_ = False

while not sorted_:
    sorted_ = True
    for i in range(length_):
        if list_[i] > list_[i + 1]:
            sorted = False
            list_[i], list_[i + 1] = list_[i + 1], list_[i]
return list_

exmaple:
a = [8,1,2,4,1,3,5,1,5,6,1,8]
bubble(a)

result:

Out[27]:
[1, 2, 4, 1, 3, 5, 1, 5, 6, 1, 8, 8]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment