python的冒泡排序算法

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

测试代码及输出:

>>> numbers = [1,3,82,77,52,2,100,90]
>>> bubblesort(numbers)
0 7
[1, 3, 82, 77, 52, 2, 100, 90]
1 7
[1, 3, 82, 77, 52, 2, 100, 90]
2 7
[1, 3, 77, 82, 52, 2, 100, 90]
3 7
[1, 3, 77, 52, 82, 2, 100, 90]
4 7
[1, 3, 77, 52, 2, 82, 100, 90]
5 7
[1, 3, 77, 52, 2, 82, 100, 90]
6 7
[1, 3, 77, 52, 2, 82, 90, 100]
0 6
[1, 3, 77, 52, 2, 82, 90, 100]
1 6
[1, 3, 77, 52, 2, 82, 90, 100]
2 6
[1, 3, 52, 77, 2, 82, 90, 100]
3 6
[1, 3, 52, 2, 77, 82, 90, 100]
4 6
[1, 3, 52, 2, 77, 82, 90, 100]
5 6
[1, 3, 52, 2, 77, 82, 90, 100]
0 5
[1, 3, 52, 2, 77, 82, 90, 100]
1 5
[1, 3, 52, 2, 77, 82, 90, 100]
2 5
[1, 3, 2, 52, 77, 82, 90, 100]
3 5
[1, 3, 2, 52, 77, 82, 90, 100]
4 5
[1, 3, 2, 52, 77, 82, 90, 100]
0 4
[1, 3, 2, 52, 77, 82, 90, 100]
1 4
[1, 2, 3, 52, 77, 82, 90, 100]
2 4
[1, 2, 3, 52, 77, 82, 90, 100]
3 4
[1, 2, 3, 52, 77, 82, 90, 100]
0 3
[1, 2, 3, 52, 77, 82, 90, 100]
1 3
[1, 2, 3, 52, 77, 82, 90, 100]
2 3
[1, 2, 3, 52, 77, 82, 90, 100]
0 2
[1, 2, 3, 52, 77, 82, 90, 100]
1 2
[1, 2, 3, 52, 77, 82, 90, 100]
0 1
[1, 2, 3, 52, 77, 82, 90, 100]

posted @ 2011-05-13 16:16  狼哥2  阅读(7485)  评论(0编辑  收藏  举报