데이터 범위가 10,000,000을 넘어가는 경우(천만 이상 초대량의 탐색 필요 시)
이진탐색은 기본적으로 "정렬"이 되어있는 상태!
그리고 Pivot을 사용한다!
주의사항 : 타겟을 제외한 모든 값은 index 넘버로 사용함을 주의하자!!
(중요) 활용 방법은 다음과 같음
# 타겟을 제외한 모든 값은 index 넘버로 사용함을 주의하자!!
def bin_search(array, target, start, end):
while start <= end:
pivot = (start + end) // 2
if target == array[pivot]:
return pivot
# 찾지 못한 경우 index값을 당겨준다!!!
elif target < array[pivot]:
end = pivot-1
elif target > array[pivot]:
start = pivot+1
return None # (중요) 도출할 결과 없으면 이렇게!!! <-- DFS에서도 써먹어
n = 10
target = 7
array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
result = bin_search(array, target, 0, n-1)
if result:
print("Target's index num = ", result)
else:
print("해당 원소가 없음")
def binarySearch(array, value, low, high):
if low > high:
return False
mid = (low+high) / 2
if array[mid] > value:
return binarySearch(array, value, low, mid-1)
elif array[mid] < value:
return binarySearch(array, value, mid+1, high)
else:
return mid
from bisect import bisect
from bisect import bisect_left, bisect_right
bisect_left(정렬된 배열, 찾을값) : 왼쪽 "인덱스"를 구하기
이렇게 생각하는 방법이 있고
이렇게 생각하는 방법이 있겠다
from bisect import bisect_left, bisect_right
nums = [0,1,2,3,4,5,6,7,8,9]
n = 5
print(bisect_left(nums, n))
print(bisect_right(nums, n))
'''
결과값
5
6
'''
from bisect import bisect_left, bisect_right
nums = [4, 5, 5, 5, 5, 5, 5, 5, 5, 6]
n = 5
print(bisect_left(nums, n))
print(bisect_right(nums, n))
'''
결과값
1
9
'''