Binary Search 재귀함수 구현 (Python)

강기호·2022년 10월 7일
0

Algorithm

목록 보기
4/14

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))

0개의 댓글