forked from OmkarPathak/pygorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpolation_search.py
More file actions
65 lines (49 loc) · 1.49 KB
/
interpolation_search.py
File metadata and controls
65 lines (49 loc) · 1.49 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
Author: SHARAD BHAT
Created On: 22nd August 2017
- Best O(1)
- Average O(log(logn))
- Worst O(n)
"""
import inspect
def search(_list, target):
"""
This function performs an interpolation search
on a sorted list and returns the index
of item if successful else returns False
:param _list: list to search
:param target: item to search for
:return: index of item if successful else returns False
"""
if type(_list) is not list:
raise TypeError("interpolation search only accepts lists, not {}".format(str(type(_list))))
# First element
low = 0
# Last element
high = len(_list) - 1
# List is assumed to be sorted
while low <= high and target >= _list[low] and target <= _list[high]:
position = low + int(((float(high - low) / (_list[high] - _list[low])) * (target - _list[low])))
if _list[position] == target:
return position
# If target is greater, search in right half
if _list[position] < target:
low = position + 1
# If target is smaller, search in left half
else:
high = position - 1
return False
def time_complexities():
"""
Return information on functions
time complexity
:return: string
"""
return "Best Case: O(1), Average Case: O(log(logn)), Worst Case: O(logn)"
def get_code():
"""
easily retrieve the source code
of the function
:return: source code
"""
return inspect.getsource(search)