-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathbsearch.py
More file actions
28 lines (23 loc) · 779 Bytes
/
bsearch.py
File metadata and controls
28 lines (23 loc) · 779 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
def binary_search(alist, token):
'''function implements binary search algorithm using slicing
@author kgashok
@param alist is list of numbers to be searched
@param token is the number to be find in the list
@returns True if present, else False
>>> binary_search([0, 1, 2, 3, 4], 2)
True
'''
while alist:
mid = len(alist) // 2
midvalue = alist[mid]
if token is midvalue:
return True
if token < midvalue:
# for e.g. token is 3, and midvalue is 5
# throw/slice away the upper half
alist = alist[:mid]
else:
# if token is 7, and midvalue is 5
# throw/slice away the lower half
alist = alist[mid + 1:]
return False