forked from bregman-arie/devops-exercises
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.py
More file actions
Latest commit
28 lines (23 loc) · 818 Bytes
/
Copy pathbinary_search.py
File metadata and controls
28 lines (23 loc) · 818 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
#!/usr/bin/env python
importrandom
fromtypingimportList
defbinary_search(arr: List[int], lb: int, ub: int, target: int) ->int:
"""
A Binary Search Example which has O(log n) time complexity.
"""
iflb<=ub:
mid: int=lb+ (ub-lb) //2
ifarr[mid] ==target:
returnmid
elifarr[mid] <target:
returnbinary_search(arr, mid+1, ub, target)
else:
returnbinary_search(arr, lb, mid-1, target)
else:
return-1
if__name__=='__main__':
rand_num_li: List[int] =sorted([random.randint(1, 50) for_inrange(10)])
target: int=random.randint(1, 50)
print("List: {}\nTarget: {}\nIndex: {}".format(
rand_num_li, target,
binary_search(rand_num_li, 0, len(rand_num_li) -1, target)))