-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpolation-Search.py
55 lines (35 loc) · 1.37 KB
/
Interpolation-Search.py
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
######Iterative Approach###########
#low = first index = 0
#high = last index = len(arr) -1
#value = element to be searched
def interpolationSearch(arr,low,high,value):
while (low<=high and value >= arr[low] and value <= arr[high]) :
# Finding the optimal position to divide (or split) the array
# The idea is to find the position closer to searched value
pos = low + (high-low)//(arr[high]-arr[low]) * (value-arr[low])
if arr[pos] == value:
return pos
elif arr[pos] < value:
low = pos + 1
else:
high = pos - 1
return -1
######Recursive Approach##########
def interpolationSearch1(arr,low,high,value):
if (low<=high and value >= arr[low] and value <= arr[high]):
pos = low + (high-low) // (arr[high]-arr[low]) * (value-arr[low])
if arr[pos] == value:
return pos
elif arr[pos] < value:
return interpolationSearch1(arr, pos+1,high,value)
else:
return interpolationSearch1(arr, low, pos-1,value)
return -1
#driver code
array = list(map(int,input("Enter your array (as space separated integers) : ").split()))
value = int(input("Enter the value to be searched : "))
result = interpolationSearch(array,0, len(array)-1,value)
if result == -1:
print("Not Found")
else:
print(value,"found at index", result)