Реалізація selection sort
У попередньому відео ви розглянули алгоритм selection sort.
У цій вправі вам потрібно реалізувати його, доповнивши функцію selection_sort().
Ця вправа є частиною курсу
Структури даних і алгоритми в 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)