一、冒泡演算法實例: a = [32,5,22,41,7,31,12,102,74,37,9,25] 1、方法1: for i in range(len(a)): for j in range(len(a)-1): if a[j] > a [j+1]: tmp = a[j] a[j] = a[j+1]
一、冒泡演算法實例:
a = [32,5,22,41,7,31,12,102,74,37,9,25]
1、方法1:
for i in range(len(a)):
for j in range(len(a)-1):
if a[j] > a [j+1]:
tmp = a[j]
a[j] = a[j+1]
a[j+1] = tmp
print(a)
註:此方法會迴圈12*11次,會進行多次不必要的判斷
2、方法2:
for i in range(len(a)):
for j in range(len(a)-i):
if a[j] > a [j+1]:
tmp = a[j]
a[j] = a[j+1]
a[j+1] = tmp
print(a)
註:此方法即正常迴圈
3、方法3: