순차 탐색 : 리스트 안에 있는 특정한 데이터를 찾기 위해 앞에서부터 데이터를 하나씩 확인 하는 방법
이진 탐색 : 정렬 되어 있는 리스트에서 탐색 범위를 절반씩 좁혀가며 데이터를 탐색하는 방법
-> 이진 탐색은 시작접, 끝점, 중간점을 이용하여 탐색 범위를 설정
-> 단계마다 탐색 범위를 2로 나누는 것과 동일하므로 연산횟수는 에 비례. 즉, 시간 복잡도는 이다.
#이진 탐색 재귀적 구현
def binary_search(array, target, start, end):
if start > end:
return None
mid = (start + end) // 2
if array[mid] == target:
return mid
elif array[mid] > target:
return binary_search(array, target, start, mid - 1)
else:
return binary_search(array, target, mid + 1, end)
n, target = list(map(int, input().split()))
array = list(map(int, input().split()))
result = binary_search(array, target, 0, n - 1)
if result == None:
print('원소가 존재하지 않는다.')
else:
print(result + 1)
# 이진 탐색 반복문 구현
def binary_search(array, target, start, end):
while start <= end:
mid = (start + end) // 2
if array[mid] == target:
return mid
elif array[mid] > target:
end = mid - 1
else:
start = mid + 1
return None
n, target = list(map(int, input().split()))
array = list(map(int, input().split()))
result = binary_search(array, target, 0, n - 1)
if result == None:
print('원소가 존재하지 않는다.')
else:
print(result + 1)
파이썬 이진 탐색 라이브러리가 있다.
# 값이 특정 범위에 속하는 데이터 개수 구하기
from bisect import bisect_left, bisect_right
def count_by_range(a, left_value, right_value):
right_index = bisect_right(a, right_value)
left_index = bisect_left(a, left_value)
return right_index - left_index
a = [1, 2, 3, 3, 3, 3, 4 , 4, 8, 9]
print(count_by_range(a, 4, 4))
print(count_by_range(a, -1, 3))