본문 바로가기
leetcode 풀이/기본 알고리즘

[기본 알고리즘] Binary Search

by 튼튼한개발자 2022. 8. 28.

 

print('Hello, world!')

l = [1,2,3,4,5,6,7,8,9,10]

target = 4
def binarySearch(l):

  left = 0
  right = len(l) - 1
  step = 0 
  while left <= right:    
    pivot = (left + right) // 2  
    
    if l[pivot] > target:
      right = pivot - 1
    elif l[pivot] < target:
      left = pivot + 1      
    else :
      return pivot
  return -1


print(binarySearch(l))

재귀 / 반복문으로 풀 수 있지만, 이왕이면 재귀를 지양하자는 의미에서 반복문으로만 풀어봄

댓글