python实现的冒泡排序算法的代码

发布时间:2020-08-26编辑:脚本学堂
python实现的冒泡排序算法的代码

python实现的冒泡排序算法的代码,供大家学习参考。
 

复制代码 代码如下:
#!/usr/bin/python
#-*-coding:UTF-8-*-
#冒泡排序算法
def sortNum(numlist):
    _numlen = len(numlist)
    for _num1 in xrange(_numlen - 1,0,-1):
        for _num2 in xrange(_num1 - 1,-1,-1):
            if numlist[_num1] < numlist[_num2]:
                (numlist[_num1],numlist[_num2]) = (numlist[_num2],numlist[_num1])
 
if __name__ == '__main__':
    a = [1,4,-12,100,3,9,7,87,7,6,12,]
 
    print "sort previous: ",
    for iter in a:
        print iter,
    sortNum(a)
 
    print "nafter sorted: ",
    for i in a:
        print i,

下面是执行过程:
 

复制代码 代码如下:
[root@localhost py_excise]# ./sortnum.py
sort previous:  1 4 -12 100 3 9 7 87 7 6 12
after sorted:  -12 1 3 4 6 7 7 9 12 87 100