想法:兩兩交插比對
程式初稿:
aArray = [8 , 2 , 9, 7 , 3]
print("Before",aArray)
for index,item in enumerate(aArray):
type(index)
print (str(index) +":"+ str(aArray[index]))
print("After:",aArray)
目前結果:
Before [8, 2, 9, 7, 3]
0:8
1:2
2:9
3:7
4:3
After: [8, 2, 9, 7, 3]
希望結果:
Before [8, 2, 9, 7, 3]
After: [2, 3, 7, 8 ,9]
完成版:最簡單的氣泡排法
aArray = [8 , 2 , 9, 7 , 3 ]
print("Before",aArray)
for i,item in enumerate(aArray):
for j,item2 in enumerate(aArray):
if aArray[i]<aArray[j]:
temp=aArray[i]
aArray[i]=aArray[j]
aArray[j]=temp
print ("[sorting]:",aArray)
print("After:",aArray)
Before [8, 2, 9, 7, 3, 1]
[sorting]: [8, 2, 9, 7, 3, 1]
[sorting]: [2, 8, 9, 7, 3, 1]
[sorting]: [2, 8, 9, 7, 3, 1]
[sorting]: [2, 7, 8, 9, 3, 1]
[sorting]: [2, 3, 7, 8, 9, 1]
[sorting]: [1, 2, 3, 7, 8, 9]
After: [1, 2, 3, 7, 8, 9]
其實還可以優化