InterpolationSearch (#7575)

This commit is contained in:
Pazis 2019-08-16 10:34:45 +04:30 committed by maibin
parent 4562a2fa07
commit d84f97cf7e
2 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package com.baeldung.algorithms.interpolationsearch;
public class InterpolationSearch {
public static int interpolationSearch(int[] data, int item) {
int highEnd = (data.length - 1);
int lowEnd = 0;
while (item >= data[lowEnd] && item <= data[highEnd] && lowEnd <= highEnd) {
int probe = lowEnd + (highEnd - lowEnd) * (item - data[lowEnd]) / (data[highEnd] - data[lowEnd]);
if (highEnd == lowEnd) {
if (data[lowEnd] == item) {
return lowEnd;
} else {
return -1;
}
}
if (data[probe] == item) {
return probe;
}
if (data[probe] < item) {
lowEnd = probe + 1;
} else {
highEnd = probe - 1;
}
}
return -1;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.algorithms.interpolationsearch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class InterpolationSearchUnitTest {
private int[] myData;
@Before
public void setUp() {
myData = new int[]{13,21,34,55,69,73,84,101};
}
@Test
public void givenSortedArray_whenLookingFor84_thenReturn6() {
int pos = InterpolationSearch.interpolationSearch(myData, 84);
assertEquals(6, pos);
}
@Test
public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
int pos = InterpolationSearch.interpolationSearch(myData, 19);
assertEquals(-1, pos);
}
}