首页 > 代码库 > 利用python实现冒泡排序

利用python实现冒泡排序

1、先生存一个随机数组成的list

2、然后进行排序,把大的元素放在后面,小的元素放在前面,最终实现从小到大排列

首先生存一个随机数组成的list

import random
# print(sys.path)
# print(__file__)
l1 = []
for i in range(6):
    i = random.randrange(0,165535)
    l1.append(i)
print(l1)

[72764, 163851, 54255, 51053, 106289, 48579]

 

然后对这个列表进行排序

r = len(l1)
for m in range(r-1):
    a = 0
    for n in range(r-1):
        if l1[a] > l1[a + 1]:
             tmp_before = l1[a]
             tmp_after = l1[a + 1]
             l1[a] = tmp_after
             l1[a + 1] = tmp_before
             # print(l1)
        elif l1[a] == l1[a + 1]:
            s = "l1[%s]和l1[%s]相等,这次不用替换" %(a,a+1)
            print(s.center(40,"-"))
            pass
        else:
            s = "l1[%s]比l1[%s]小,这次不用替换" % (a, a + 1)
            print(s.center(40,"-"))
            pass
        a += 1

print(l1)

[48579, 51053, 54255, 72764, 106289, 163851]

 

利用python实现冒泡排序