python 選擇排序
阿新 • • 發佈:2018-02-13
span 選擇排序 結果 標記 nbsp class 排序 pos 輸出
選擇排序:
思想:每次選擇出最小的值依次放到最前面
代碼:
1 a = [9,1,22,31,45,3,6,2,11]
3 for i in range(len(a)-1): 4 index = i #index標記最小的 值 假設第一個是最小的值 5 for j in range(i+1,len(a)): 6 if a[index] > a[j]: 7 index = j #index 一直指向最小的值 8 a[i],a[index] = a[index],a[i] #讓a[index] 與 第[i]個值 互換 ,達到排序 9 print(a)
輸出結果:[1, 2, 3, 6, 9, 11, 22, 31, 45]
過程:
[9, 1, 22, 31, 45, 3, 6, 2, 11]
[1, 9, 22, 31, 45, 3, 6, 2, 11]
[1, 2, 22, 31, 45, 3, 6, 9, 11]
[1, 2, 3, 31, 45, 22, 6, 9, 11]
[1, 2, 3, 6, 45, 22, 31, 9, 11]
[1, 2, 3, 6, 9, 22, 31, 45, 11]
[1, 2, 3, 6, 9, 11, 31, 45, 22]
[1, 2, 3, 6, 9, 11, 22, 45, 31]
[1, 2, 3, 6, 9, 11, 22, 31, 45]
python 選擇排序