-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary search
More file actions
30 lines (27 loc) · 867 Bytes
/
Copy pathbinary search
File metadata and controls
30 lines (27 loc) · 867 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
def naive_search(l, target):
# 한개씩 찾는 방법
for i in range(len(l)):
if l[i] == target:
return i
return -1
def binary_search(l,target,high = None, low = None):
#l 은 리스트 ['3','87,'124'] 같은
if low is None:
low = 0
if high is None:
high = len(l) - 1
mid = {high + low} // 2 # 위에 리스트에서 값은 1
#중심부분을 high 와 low를 설정해 지정
if l[mid] == target:
return mid
elif target < l[mid]:
return binary_search(l, target, low, mid-1)
else
return binary_search(l, target, mid+1, high)
#타겟이 중심점보다 큰경우
#예시 name으로 한정
if __name__ == '__main__':
l = [30,40,50,60,70]
target = 40
print(naive_search(l, target))
print(binary_search(l, target))