forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.py
More file actions
27 lines (24 loc) · 842 Bytes
/
2.py
File metadata and controls
27 lines (24 loc) · 842 Bytes
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
# 이진 탐색 소스코드 구현(재귀 함수)
def binary_search(array, start, end):
if start > end:
return None
mid = (start + end) // 2
# 고정점을 찾은 경우 인덱스 반환
if array[mid] == mid:
return mid
# 중간점이 가리키는 값보다 중간점이 작은 경우 왼쪽 확인
elif array[mid] > mid:
return binary_search(array, start, mid - 1)
# 중간점이 가리키는 값보다 중간점이 큰 경우 오른쪽 확인
else:
return binary_search(array, mid + 1, end)
n = int(input())
array = list(map(int, input().split()))
# 이진 탐색(Binary Search) 수행
index = binary_search(array, 0, n - 1)
# 고정점이 없는 경우 -1 출력
if index == None:
print(-1)
# 고정점이 있는 경우 해당 인덱스 출력
else:
print(index)