-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.py
More file actions
33 lines (27 loc) · 861 Bytes
/
binary_search.py
File metadata and controls
33 lines (27 loc) · 861 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
28
29
30
31
32
33
def binary_search_recur(arr, target, start, end):
if start > end:
return None
mid = (start + end) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
return binary_search_recur(arr, target, start, mid - 1)
else:
return binary_search_recur(arr, target, mid + 1, end)
def binary_search_iter(arr, target, start, end):
while start <= end:
mid = (start + end) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
end = mid - 1
else:
start = mid + 1
return None
n, target = map(int, input().split())
arr = list(map(int, input().split()))
result = binary_search_iter(arr, target, 0, n - 1)
if result == None:
print("Not exist")
else:
print(str(result + 1) + "th")