代码改变世界

Algorithm - Bubble sort

2021-06-23 16:29  WayneWei  阅读(39)  评论(0编辑  收藏  举报

Python implement algorithm Bubble sort:

# Bubble sort

mylist = [3, 6, 9, 2, 5, 8, 1, 4, 7]

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

bubblesort(mylist)
print(mylist)

Testing output as below:

D:\test\venv\Scripts\python.exe D:/test/algorithm.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Process finished with exit code 0