Algorithm(알고리즘)/기본
3) 이진탐색 (Binary search)
반응형
##### 3. 이진탐색 : 절반으로 잘라가며 요소 찾기
def binary_search(element, some_list):
start_index = 0
end_index = len(some_list) - 1
while start_index <= end_index:
midpoint = (start_index + end_index) // 2
if some_list[midpoint] == element:
return midpoint
elif some_list[midpoint] > element:
end_index = midpoint - 1
else:
start_index = midpoint + 1
return None
print(binary_search(2, [2, 3, 5, 7, 11]))
print(binary_search(0, [2, 3, 5, 7, 11]))
print(binary_search(5, [2, 3, 5, 7, 11]))
print(binary_search(3, [2, 3, 5, 7, 11]))
print(binary_search(11, [2, 3, 5, 7, 11]))
반응형
'Algorithm(알고리즘) > 기본' 카테고리의 다른 글
2) 선형탐색 (Linear search) (0) | 2021.05.13 |
---|---|
1) palindrome : 앞뒤가 같은 단어 찾기 (for문) (0) | 2021.05.13 |
댓글