Python bubble sort algorithm implementation code
- 2020-04-02 13:11:35
- OfStack
1. Algorithm description:
(1) a total of n-1 cycles
(2) in each cycle, if the preceding number is greater than the following number, it is swapped
(3) set a label, if there is no exchange last time, this is already good.
Python bubble sort code
#!/usr/bin/python
# -*- coding: utf-8 -*-
def bubble(l):
flag = True
for i in range(len(l)-1, 0, -1):
if flag:
flag = False
for j in range(i):
if l[j] > l[j + 1]:
l[j], l[j+1] = l[j+1], l[j]
flag = True
else:
break
print l
li = [21,44,2,45,33,4,3,67]
bubble(li)
Results: [2, 3, 4, 21, 33, 44, 45, 67]