- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathinterpolation_search.py
81 lines (38 loc) · 1.31 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Python3 program to implement
# interpolation search
# with recursion
# If x is present in arr[0..n-1], then
# returns index of it, else returns -1.
definterpolationSearch(arr, lo, hi, x):
# Since array is sorted, an element present
# in array must be in range defined by corner
if (lo<=hiandx>=arr[lo] andx<=arr[hi]):
# Probing the position with keeping
# uniform distribution in mind.
pos=lo+ ((hi-lo) // (arr[hi] -arr[lo]) *
(x-arr[lo]))
# Condition of target found
ifarr[pos] ==x:
returnpos
# If x is larger, x is in right subarray
ifarr[pos] <x:
returninterpolationSearch(arr, pos+1,
hi, x)
# If x is smaller, x is in left subarray
ifarr[pos] >x:
returninterpolationSearch(arr, lo,
pos-1, x)
return-1
# Driver code
# Array of items in which
# search will be conducted
arr= [10, 12, 13, 16, 18, 19, 20,
21, 22, 23, 24, 33, 35, 42, 47]
n=len(arr)
# Element to be searched
x=18
index=interpolationSearch(arr, 0, n-1, x)
ifindex!=-1:
print("Element found at index", index)
else:
print("Element not found")