Fix division by zero in interpolation search#7484
Open
priyanshuvishwakarma273403 wants to merge 2 commits into
Open
Fix division by zero in interpolation search#7484priyanshuvishwakarma273403 wants to merge 2 commits into
priyanshuvishwakarma273403 wants to merge 2 commits into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #7484 +/- ##
============================================
+ Coverage 79.85% 79.86% +0.01%
- Complexity 7328 7331 +3
============================================
Files 807 807
Lines 23817 23819 +2
Branches 4687 4688 +1
============================================
+ Hits 19018 19023 +5
Misses 4036 4036
+ Partials 763 760 -3 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
This PR fixes a
java.lang.ArithmeticException: / by zeroinInterpolationSearch.find(...)and resolves an issue with the interpolation calculation logic.Related Issue
Fixes #7466
Changes Made
if (array[start] == array[end])inside the search loop. If the bounds are equal and the search key lies within them, it returnsstartdirectly. This avoids division by zero when calculating the probing position.longbefore performing division:int pos = start + (int) (((long) (end - start) * (key - array[start])) / ((long) array[end] - array[start]));This prevents truncation from integer division (which was causing the algorithm to fallback to a linear search in most cases) and prevents integer overflow.
testInterpolationSearchDivisionByZeroEdgeCasesinInterpolationSearchTest.javacovering the cases described in the issue:[0, 0, 0, 2], 2 -> 3[2, 2, 2, 2], 2 -> 0[0, 1, 2, 4], 4 -> 3Checklist