Skip to content

Commit 4e470ba

Browse files
committed
Added Binary Search
1 parent e9a5866 commit 4e470ba

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

pygorithm/searching/binary_search.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Author: OMKAR PATHAK
2+
# Created On: 1st August 2017
3+
4+
# Best O(1); Average O(logn); Worst O(logn)
5+
6+
def search(List, target):
7+
'''This function performs a binary search on a sorted list and returns the position if successful else returns -1'''
8+
left = 0 # First position of the list
9+
right = len(List) - 1 # Last position of the list
10+
11+
try:
12+
while left <= right: # you can also write while True condition
13+
mid = (left + right) // 2
14+
if target == List[mid]:
15+
return mid
16+
elif target < List[mid]:
17+
right = mid - 1
18+
else:
19+
left = mid + 1
20+
return -1
21+
except TypeError:
22+
return -1
23+
24+
25+
# time complexities
26+
def bestcase_complexity():
27+
return 'O(1)'
28+
29+
def averagecase_complexity():
30+
return 'O(logn)'
31+
32+
def worstcase_complexity():
33+
return 'O(logn)'
34+
35+
# easily retrieve the source code of the sort function
36+
def get_code():
37+
import inspect
38+
return inspect.getsource(search)

0 commit comments

Comments
 (0)