Skip to content

Commit 5d87c30

Browse files
authored
Added Interpolation Search in Python
1 parent 510d117 commit 5d87c30

File tree

1 file changed

+127
-0
lines changed

1 file changed

+127
-0
lines changed
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
#Interpolation Search
2+
#Better than binary search as it returns a closer value of pos on each iteration.
3+
#pos=low +[x-arr[low]*(high-low)/arr[high]-arr[low]]
4+
5+
#iterative implememtation of interpolation search
6+
7+
def interpolationSearch(L,e):
8+
9+
low=0
10+
high=len(L)-1
11+
12+
while low<=high and e >=L[low] and e <=L[high]:
13+
pos=low + int((high-low)/(L[high]-L[low])*(e-L[low]))
14+
15+
print(pos)
16+
17+
if L[pos]==e:
18+
return pos
19+
20+
if L[pos]<e:
21+
low=pos+1
22+
23+
if L[pos]>e:
24+
high=pos-1
25+
26+
27+
return -1
28+
29+
30+
L = [123,
31+
134,
32+
149,
33+
169,
34+
210,
35+
219,
36+
229,
37+
234,
38+
239,
39+
245,
40+
257,
41+
275,
42+
277,
43+
281,
44+
286,
45+
295,
46+
304,
47+
315,
48+
331,
49+
334,
50+
338,
51+
349,
52+
352,
53+
366,
54+
385,
55+
391,
56+
392,
57+
401,
58+
413,
59+
436,
60+
442,
61+
453,
62+
480,
63+
499,
64+
501,
65+
505,
66+
509,
67+
511,
68+
516,
69+
521,
70+
527,
71+
536,
72+
560,
73+
562,
74+
568,
75+
589,
76+
601,
77+
636,
78+
648,
79+
649,
80+
659,
81+
660,
82+
666,
83+
678,
84+
689,
85+
700,
86+
733,
87+
739,
88+
754,
89+
755,
90+
776,
91+
798,
92+
808,
93+
809,
94+
818,
95+
828,
96+
834,
97+
842,
98+
846,
99+
856,
100+
857,
101+
858,
102+
859,
103+
869,
104+
889,
105+
891,
106+
893,
107+
895,
108+
900,
109+
918,
110+
930,
111+
934,
112+
949,
113+
953,
114+
963,
115+
979,
116+
980,
117+
989,
118+
991,
119+
]
120+
121+
e = 8931# Element to be searched
122+
index = interpolationSearch(L,e)
123+
124+
if index != -1:
125+
print("Element found at index",index)
126+
else:
127+
print("Element not found")

0 commit comments

Comments
 (0)