File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Author: SHARAD BHAT
3
+ Created On: 22nd August 2017
4
+
5
+ - Best O()
6
+ - Average O(log(logn))
7
+ - Worst O(n)
8
+ """
9
+
10
+ import inspect
11
+
12
+ def search (_list , target ):
13
+ """
14
+ This function performs an interpolation search
15
+ on a sorted list and returns the index
16
+ of item if successful else returns False
17
+
18
+ :param _list: list to search
19
+ :param target: item to search for
20
+ :return: index of item if successful else returns False
21
+ """
22
+
23
+ if type (_list ) is not list :
24
+ raise TypeError ("binary search only excepts lists, not {}" .format (str (type (_list ))))
25
+
26
+ # First element
27
+ low = 0
28
+ # Last element
29
+ high = len (_list ) - 1
30
+
31
+ # List is assumed to be sorted
32
+ while low <= high and target >= _list [low ] and target <= _list [high ]:
33
+ position = low + int (((float (high - low ) / (_list [high ] - _list [low ])) * (target - _list [low ])))
34
+
35
+ if _list [position ] == target :
36
+ return position
37
+
38
+ # If target is greater, search in right half
39
+ if _list [position ] < target :
40
+ low = position + 1
41
+
42
+ # If target is smaller, search in left half
43
+ else :
44
+ high = position - 1
45
+
46
+ return False
47
+
48
+
49
+
50
+ def time_complexities ():
51
+ """
52
+ Return information on functions
53
+ time complexity
54
+ :return: string
55
+ """
56
+ return "Best Case: O(1), Average Case: O(log(logn)), Worst Case: O(logn)"
57
+
58
+
59
+ def get_code ():
60
+ """
61
+ easily retrieve the source code
62
+ of the function
63
+ :return: source code
64
+ """
65
+ return inspect .getsource (search )
You can’t perform that action at this time.
0 commit comments