File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments