Algorithm
[알고리즘] 이진 탐색 알고리즘 (Binary Search Algorithm)
주씨.
2022. 1. 2. 11:09
728x90
재귀 함수를 이용한 이진 탐색
def binary_search(arr, target, start, end):
if start > end:
return None
mid = (start + end) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search(arr, target, start, mid -1)
else:
return binary_search(arr, target, mid + 1, end)
반복문을 이용한 이진 탐색
def binary_search(arr, target, start, end):
while start <= end:
mid = (start + end) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
end = mid - 1
else:
start = mid + 1
return None
bisect_left(a, x) : 정렬된 순서를 유지하면서 리스트 a에 데이터 x를 삽입할 가장 왼쪽 인덱스를 찾는 메서드
bisect_right(a, x) : 정렬된 순서를 유지하면서 리스트 a에 데이터 x를 삽입할 가장 오른쪽 인덱스를 찾는 메서드
def bisect_left(arr, target, low=0, high=None):
if high is None:
high = len(arr)
while low < high:
mid = (low + high) // 2
if arr[mid] < target:
low = mid+1
else:
high = mid
return low
def bisect_right(arr, target, low=0, high=None):
if high is None:
high = len(arr)
while low < high:
mid = (low + high) // 2
if target < arr[mid]:
high = mid
else:
low = mid+1
return high
bisect_left() 함수와 bisect_right()함수는 '정렬된 리스트'에서 '값이 특정 범위에 속하는 원소의 개수를 구하고자 할 때, 효과적으로 사용될 수 있다.
파이썬에서는 이진 탐색을 쉽게 구현할 수 있도록 bisect 라이브러리를 제공한다. 두 함수는 O(logN)에 동작한다.
위의 코드는 파이썬에 내장된 bisect_left(), bisect_right()의 실제 소스코드이다.
from bisect import bisect_left, bisect_right
a = bisect_left(arr, x)
b = bisect_right(arr, x)
에서 a==b 이면 arr에 x가 존재하지 않는다는 뜻이다.