Skip to content

Commit d84f97c

Browse files
afshar-mohammadmaibin
authored andcommitted
InterpolationSearch (eugenp#7575)
1 parent 4562a2f commit d84f97c

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.baeldung.algorithms.interpolationsearch;
2+
3+
public class InterpolationSearch {
4+
5+
public static int interpolationSearch(int[] data, int item) {
6+
7+
int highEnd = (data.length - 1);
8+
int lowEnd = 0;
9+
10+
while (item >= data[lowEnd] && item <= data[highEnd] && lowEnd <= highEnd) {
11+
12+
int probe = lowEnd + (highEnd - lowEnd) * (item - data[lowEnd]) / (data[highEnd] - data[lowEnd]);
13+
14+
if (highEnd == lowEnd) {
15+
if (data[lowEnd] == item) {
16+
return lowEnd;
17+
} else {
18+
return -1;
19+
}
20+
}
21+
22+
if (data[probe] == item) {
23+
return probe;
24+
}
25+
26+
if (data[probe] < item) {
27+
lowEnd = probe + 1;
28+
} else {
29+
highEnd = probe - 1;
30+
}
31+
}
32+
return -1;
33+
}
34+
35+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.baeldung.algorithms.interpolationsearch;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.Before;
6+
import org.junit.Test;
7+
8+
public class InterpolationSearchUnitTest {
9+
10+
private int[] myData;
11+
12+
@Before
13+
public void setUp() {
14+
myData = new int[]{13,21,34,55,69,73,84,101};
15+
}
16+
17+
@Test
18+
public void givenSortedArray_whenLookingFor84_thenReturn6() {
19+
int pos = InterpolationSearch.interpolationSearch(myData, 84);
20+
assertEquals(6, pos);
21+
}
22+
23+
@Test
24+
public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
25+
int pos = InterpolationSearch.interpolationSearch(myData, 19);
26+
assertEquals(-1, pos);
27+
}
28+
29+
}

0 commit comments

Comments
 (0)