버블 정렬 알고리즘의 버그 고치기
bubble sort 알고리즘으로 숫자 리스트를 정렬하는 프로그램이 주어졌어요. 테스트해 보니 코드에 오류가 있네요. 알고리즘이 올바르게 동작하도록 수정해 보시겠어요?
이 연습은 강의의 일부입니다
Python으로 배우는 자료구조와 알고리즘
연습 안내
is_sorted변수의 할당에서 난 mistake을(를) 고치세요.- 인접한 값을 검사하는 부분의 mistake을(를) 고치세요.
list_length변수 값을 업데이트하는 부분의 mistake을(를) 고치세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
def bubble_sort(my_list):
list_length = len(my_list)
# Correct the mistake
is_sorted = True
while not is_sorted:
is_sorted = True
for i in range(list_length-1):
# Correct the mistake
if my_list[i] < my_list[i+1]:
my_list[i] , my_list[i+1] = my_list[i+1] , my_list[i]
is_sorted = False
# Correct the mistake
list_length += 1
return my_list
print(bubble_sort([5, 7, 9, 1, 4, 2]))