Skip to content

Commit e57a675

Browse files
Fix division by zero in interpolation search (#7484)
* Fix division by zero in interpolation search * style: fix formatting in InterpolationSearchTest
1 parent fafc5a2 commit e57a675

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

src/main/java/com/thealgorithms/searches/InterpolationSearch.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,12 @@ public int find(int[] array, int key) {
3636
// Since array is sorted, an element present
3737
// in array must be in range defined by corner
3838
while (start <= end && key >= array[start] && key <= array[end]) {
39+
if (array[start] == array[end]) {
40+
return start;
41+
}
3942
// Probing the position with keeping
4043
// uniform distribution in mind.
41-
int pos = start + (((end - start) / (array[end] - array[start])) * (key - array[start]));
44+
int pos = start + (int) (((long) (end - start) * (key - array[start])) / ((long) array[end] - array[start]));
4245

4346
// Condition of target found
4447
if (array[pos] == key) {

src/test/java/com/thealgorithms/searches/InterpolationSearchTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,4 +87,15 @@ void testInterpolationSearchLargeNonUniformArray() {
8787
int key = 21; // Present in the array
8888
assertEquals(6, interpolationSearch.find(array, key), "The index of the found element should be 6.");
8989
}
90+
91+
/**
92+
* Test for interpolation search with specific sorted arrays that previously caused division by zero.
93+
*/
94+
@Test
95+
void testInterpolationSearchDivisionByZeroEdgeCases() {
96+
InterpolationSearch interpolationSearch = new InterpolationSearch();
97+
assertEquals(3, interpolationSearch.find(new int[] {0, 0, 0, 2}, 2));
98+
assertEquals(0, interpolationSearch.find(new int[] {2, 2, 2, 2}, 2));
99+
assertEquals(3, interpolationSearch.find(new int[] {0, 1, 2, 4}, 4));
100+
}
90101
}

0 commit comments

Comments
 (0)