이분탐색은 정렬된 데이터에서 특정 값을 효율적으로 찾기 위한 알고리즘입니다. 이 알고리즘은 O(log n)의 시간 복잡도를 가집니다. 아래에서는 C와 Python에서 이분탐색을 어떻게 구현할 수 있는지 살펴보겠습니다.
bsearch
함수를 제공하기도 하지만, 대부분의 경우 직접 구현합니다.#include <stdio.h>
int binary_search(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int index = binary_search(arr, 5, 3);
if (index != -1) printf("Element found at index %d\n", index);
else printf("Element not found\n");
return 0;
}
bisect
모듈을 사용하면 더 간편하게 이분탐색을 수행할 수 있습니다.from bisect import bisect_left
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
if arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
arr = [1, 2, 3, 4, 5]
index = binary_search(arr, 3)
if index != -1:
print(f"Element found at index {index}")
else:
print("Element not found")
# Using bisect module
index = bisect_left(arr, 3)
if index != len(arr) and arr[index] == 3:
print(f"Element found at index {index}")
else:
print("Element not found")