C언어로 구현했던 Binary Search를 파이썬으로 구현해보자
Python 구현
def BinarySearch(arr_ , start_ , end_ , value_):
if(start_ > end_):
return -1
elif (start_ == end_):
if arr_[start_] == value_:
return start_
else:
return -1
else:
mid = int((start_ + end_)/2)
if arr_[mid] == value_:
return mid
elif(arr_[mid] > value_):
return BinarySearch(arr_ , start_ , mid-1 , value_)
else:
return BinarySearch(arr_ , mid+1 , end_ , value_)
n, value = map(int , input().split())
arr = list(map(int , input().split()))
idx = BinarySearch(arr , 0 , n-1 , value)
if (idx == -1):
print("can't find value")
else:
print("find value !! , idx = {}".format(idx))