實作 selection sort
在上一支影片中,你學習了 selection sort 演算法。
在這個練習中,你需要完成 selection_sort() 函式來實作它。
本練習屬於課程
Data Structures and Algorithms in Python
練習說明
- 將
lowest設為索引i位置的串列元素。 - 從變數
i的下一個位置開始,再次走訪整個串列。 - 比較索引
j位置的串列元素是否小於lowest。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def selection_sort(my_list):
list_length = len(my_list)
for i in range(list_length - 1):
# Set lowest to the element of the list located at index i
lowest = ____
index = i
# Iterate again over the list starting on the next position of the i variable
____ j in range(____, list_length):
# Compare whether the element of the list located at index j is smaller than lowest
if _____:
index = j
lowest = my_list[j]
my_list[i] , my_list[index] = my_list[index] , my_list[i]
return my_list
my_list = [6, 2, 9, 7, 4, 8]
selection_sort(my_list)
print(my_list)