python实现冒泡排序

代码

#!/usr/bin/python

#-*-coding:utf-8-*-

#----------------------------------------------------------------------------------------

# to_do  : bubble sort

# authors: zuoxingyu

# time   : 2014-06-07

#----------------------------------------------------------------------------------------

loop=0                                #冒泡次数

def bubble(lists):

        global loop

        listlength=len(lists)

        for i in range(listlength-1):

                if lists[i]<lists[i+1]:

                        tmp=lists[i]

                        lists[i]=lists[i+1]

                        lists[i+1]=tmp

                        loop=loop+1

                        print lists

                        bubble(lists)



bubble([1,8,5,7,10,2])

print loop

结果:

[root@meizuDB MEIZUdb]# python bubble.py 

[8, 1, 5, 7, 10, 2]

[8, 5, 1, 7, 10, 2]

[8, 5, 7, 1, 10, 2]

[8, 7, 5, 1, 10, 2]

[8, 7, 5, 10, 1, 2]

[8, 7, 10, 5, 1, 2]

[8, 10, 7, 5, 1, 2]

[10, 8, 7, 5, 1, 2]

[10, 8, 7, 5, 2, 1]

9

挺好玩的

:)

你可能感兴趣的:(python)