선택 정렬 코딩하기
지난 영상에서 selection sort 알고리즘을 살펴봤어요.
이 연습에서는 selection_sort() 함수를 완성해 직접 구현해 보세요.
이 연습은 강의의 일부입니다
Python으로 배우는 자료구조와 알고리즘
연습 안내
- 인덱스
i에 있는 리스트 요소로lowest를 설정하세요. - 변수
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)