Algorithm/이것이 코딩테스트다

[이.코.테] 이진 탐색

hammii 2021. 9. 13. 14:37
728x90
반응형

순차 탐색

  • 리스트 안에 있는 특정한 데이터를 찾기 위해 앞에서부터 데이터를 하나씩 차례대로 확인하는 방법
  • 시간복잡도:O(N)

 

이진 탐색

  • 배열 내부 데이터가 정렬되어 있어야만 사용할 수 있는 알고리즘
  • 찾으려는 데이터와 중간점 위치에 있는 데이터를 반복적으로 비교하는 방법
  • 시간복잡도:O(logN)

재귀 함수로 구현한 이진 탐색

def binary_search(array, target, start, end):
    if start > end:
        return None

    mid = (start + end) // 2
    if array[mid] == target:
        return mid
    elif array[mid] > target:
        return binary_search(array, target, start, mid - 1)
    else:
        return binary_search(array, target, mid + 1, end)

반복문으로 구현한 이진 탐색

def binary_search(array, target, start, end):
    mid = (start + end) // 2
    while start <= end:
        if array[mid] == target:
            return mid
        elif array[mid] > target:
            end = mid -1
        else:
            start = mid + 1
    return None

 

관련 라이브러리

  • 파이썬에서는 이진 탐색을 직접 구현할 필요 없이 bisect를 사용하면 편한 경우가 있다.
from bisect import bisect_left, bisect_right

a = [1,2,4,4,8]
x = 4

bisect_left(a, x)	# 2
bisect_right(a, x)	# 4
  • bisect_left(a, x): 정렬된 순서를 유지하면서 리스트 a에 데이터 x를 삽입할 가장 왼쪽 인덱스를 찾는 메서드
  • bisect_right(a, x): 정렬된 순서를 유지하면서 리스트 a에 데이터 x를 삽입할 가장 오른쪽 인덱스를 찾는 메서드

 

정렬된 배열에서 특정 범위에 속하는 원소의 개수를 찾는 문제

from bisect import bisect_left, bisect_right

def count_by_range(1, left_value, right_value):
    right_index = bisect_right(a, right_value)
    left_index = bisect_left(a, left_value)
    return right_index - left_index

 

 

 

728x90
반응형