-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.py
More file actions
39 lines (30 loc) · 905 Bytes
/
binary_search.py
File metadata and controls
39 lines (30 loc) · 905 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
34
35
36
37
def binary_search(sorted_list, item):
n =len(sorted_list)
if n > 0:
mid = n // 2
if sorted_list[mid] == item:
return True
elif item < sorted_list[mid]:
return binary_search(sorted_list[:mid], item)
else:
return binary_search(sorted_list[mid + 1:], item)
return False
def binary_search_2(sorted_list, item):
n = len(sorted_list)
first = 0
last = n - 1
while first <= last:
mid = (first + last)//2
if sorted_list[mid] == item:
return True
elif item < sorted_list[mid]:
last = mid - 1
else:
first = mid + 1
return False
if __name__ == '__main__':
li = [17, 20, 26, 31, 44, 54, 55, 77, 93]
print(binary_search(li, 55))
print(binary_search(li, 100))
print(binary_search_2(li, 55))
print(binary_search_2(li, 100))