Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

this-is-kim

[Algorithm] 이진 탐색 (Binary Search) 본문

Study/Algorithm

[Algorithm] 이진 탐색 (Binary Search)

this-is-kim 2022. 7. 26. 21:29

*순차 탐색 (Sequential Search)

-데이터를 차례대로 확인하는 방법

-시간복잡도 : O(N)

# 반복문

def sequential_search(data, target):
    for i in range(len(data)):
        if target == data[i]:
            return i + 1


data = list(input().split())
target = input()

print(sequential_search(data, target))

 

*이진 탐색 (Binary Search)

-데이터가 정렬되어있는 경우에 사용

-시작점, 중간점, 끝점

-찾으려는 데이터와 중간점 위치의 데이터를 비교

-한 번 확인할 때마다 확인할 원소의 갯수가 절반으로 줌

-시간 복잡도 : O(logN)

# 반복문

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


data = list(map(int, input().split()))
target = int(input())

print(binary_search(data, target))
# 재귀 함수

'Study > Algorithm' 카테고리의 다른 글

[Algorithm] 다이나믹 프로그래밍(Dynamic Programming)  (0) 2022.09.05
[Algorithm] 정렬(Sorting)  (0) 2022.07.25
[Algorithm] DFS/BFS  (0) 2022.07.24
[Algorithm] 구현(Implementation)  (0) 2022.06.27
[Algorithm] 탐욕법(Greedy)  (0) 2022.06.20