排序算法
冒泡
a=[111,22,233,12,3,4]
print a[::-1]
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
print alist,passnum
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
return alist
print bubbleSort(a)
详细分析
a=[111,22,233,12,33,4]
print a[::-1]
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
print alist,passnum,'!!!!!!!!'
for i in range(passnum):
if alist[i]>alist[i+1]:
alist[i] ,alist[i+1] = alist[i+1] , alist[i]
print a[i+1],'is bigger then',a[i],'so changed'
print alist
else:
print a[i],'is not bigger then',a[i+1],'so no changed'
print alist
return alist
print bubbleSort(a)结果
[111, 22, 233, 12, 33, 4] 5 !!!!!!!!
111 is bigger then 22 so changed
[22, 111, 233, 12, 33, 4]
111 is not bigger then 233 so no changed
[22, 111, 233, 12, 33, 4]
233 is bigger then 12 so changed
[22, 111, 12, 233, 33, 4]
233 is bigger then 33 so changed
[22, 111, 12, 33, 233, 4]
233 is bigger then 4 so changed
[22, 111, 12, 33, 4, 233]
[22, 111, 12, 33, 4, 233] 4 !!!!!!!!
22 is not bigger then 111 so no changed
[22, 111, 12, 33, 4, 233]
111 is bigger then 12 so changed
[22, 12, 111, 33, 4, 233]
111 is bigger then 33 so changed
[22, 12, 33, 111, 4, 233]
111 is bigger then 4 so changed
[22, 12, 33, 4, 111, 233]
[22, 12, 33, 4, 111, 233] 3 !!!!!!!!
22 is bigger then 12 so changed
[12, 22, 33, 4, 111, 233]
22 is not bigger then 33 so no changed
[12, 22, 33, 4, 111, 233]
33 is bigger then 4 so changed
[12, 22, 4, 33, 111, 233]
[12, 22, 4, 33, 111, 233] 2 !!!!!!!!
12 is not bigger then 22 so no changed
[12, 22, 4, 33, 111, 233]
22 is bigger then 4 so changed
[12, 4, 22, 33, 111, 233]
[12, 4, 22, 33, 111, 233] 1 !!!!!!!!
12 is bigger then 4 so changed
[4, 12, 22, 33, 111, 233]
[4, 12, 22, 33, 111, 233]