이진 탐색 구현하기
이 영상에서는 선형 탐색과 이진 탐색을 구현하는 방법과 두 방법의 차이를 살펴봤어요.
이 연습 문제에서는 binary_search() 함수를 직접 구현해야 합니다. 해보시겠어요?
이 연습은 강의의 일부입니다
Python으로 배우는 자료구조와 알고리즘
연습 안내
- 찾는 값이 가운데 값과 같은지 확인하세요.
- 찾는 값이 가운데 값보다 작은지 확인하세요.
last를middle에서 1을 뺀 값으로 설정하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
def binary_search(ordered_list, search_value):
first = 0
last = len(ordered_list) - 1
while first <= last:
middle = (first + last)//2
# Check whether the search value equals the value in the middle
if ____ == ____:
return True
# Check whether the search value is smaller than the value in the middle
elif ____ < ____:
# Set last to the value of middle minus one
____
else:
first = middle + 1
return False
print(binary_search([1,5,8,9,15,20,70,72], 5))