Binary Search(이진 탐색)
- 자료의 가운데에 있는 항목의 키 값과 비교하여 다음 검색의 위치 결정
- 자료가 정렬된 상태여야 함
Algorithm
a = [2, 4, 7, 9, 10, 13]
def binary_search(a, num):
start, end = 0, len(a)-1
while start <= end :
middle = (start + end)//2
if a[middle] == num :
return True
elif a[middle] > num :
end = middle - 1
else :
start = middle + 1
return False
print(binary_search(a, 11))
print(binary_search(a, 4))
def binary_search_2(a, num, start, end):
if start > end :
return False
middle = (start+end)//2
if a[middle] == num :
return True
elif a[middle] > num :
return binary_search_2(a, num, start, middle -1)
else :
return binary_search_2(a, num, middle + 1, end)
print(binary_search_2(a, 11, 0, len(a)))
print(binary_search_2(a, 4, 0, len(a)))
bisect
import bisect
a = [2, 4, 4, 7, 10, 13]
print(bisect.bisect_left(a, 3))
print(bisect.bisect_left(a, 4))
print(bisect.bisect_right(a, 4))
print(bisect.bisect(a, 4))
bisect.insort(a, 3)
print(a)