개발야옹

🌼 Binary Search (이분 탐색) 본문

Algorithm\CodingTest/이것이 코딩테스트다 with 파이썬

🌼 Binary Search (이분 탐색)

kitez 2024. 10. 9. 00:13

🌼 Binary Search (이분 탐색)

🌼 이진 탐색 알고리즘

  • 순차 탐색: 리스트 안에 있는 특정한 데이터를 찾기 위해 앞에서부터 데이터를 하나씩 확인하는 방법
  • 이진 탐색: 정렬되어 있는 리스트에 탐색 범위를 절반씩 좁혀가며 데이터를 탐색하는 방법
    • 이진 탐색은 시작점, 끝점, 중간점을 이용하여 탐색 범위를 설정합니다.

 

🌼 이진 탐색 동작 예시

  • [Step 1] 시작점: 0, 끝점: 9, 중간점: 4 (소수점 이하 제거)

  • [Step 2] 시작점: 0, 끝점: 3, 중간점: 1 (소수점 이하 제거)

  • [Step 3] 시작점: 2, 끝점: 3, 중간점: 2 (소수점 이하 제거)

 

🌼 이진 탐색의 시간 복잡도

  • 단계마다 탐색 범위를 2로 나누는 것과 동일하므로 연산 횟수는 log2N에 비례합니다.
  • 예를 들어 초기 데이터 개수가 32개일 때, 이상적으로 1단계를 거치면 16개 가량의 데이터만 남습니다./
    • 2단계를 거치면 8개가량의 데이터만 남습니다.
    • 3단계를 거치면 4개가량의 데이터만 남습니다.
  • 다시 말해 이진 탐색은 탐색 범위를 절반씩 줄이며, 시간 복잡도는 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)

n, target = map(int, input().split())

array = list(map(int, input().split()))

result = binary_search(array, target, 0, n - 1)
if result == None:
    print("원소가 존재하지 않습니다.")
else:
    print(result + 1)

 

✅ 반복문으로 구현

n, target = map(int, input().split())

array = list(map(int, input().split()))

start = 0
end = n-1

result = None
while start <= end:
    mid = (start + end) // 2
    if array[mid] < target:
        start = mid + 1
    elif array[mid] > target:
        end = mid - 1
    else:
        result = mid
        break
print(None if result == None else result + 1)

 

728x90