Repository navigation
Conversation
…eds range (fixes trekhleb#2219) interpolationSearch could loop forever when the seek element was greater than sortedArray[rightIndex] while the range still contained values above it: valueDelta could exceed rangeDelta, producing a middleIndex beyond rightIndex, so rightIndex never changed and the loop repeated. Add the symmetric early-return check (seekElement > sortedArray[rightIndex]) mirroring the existing valueDelta < 0 check. This also guarantees the interpolated middleIndex stays inside [leftIndex, rightIndex], so every iteration shrinks the search range. Add regression tests for the reported input and similar cases.
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
interpolationSearchnever returns for some inputs where the seek element is missing:Trace: the first pass interpolates index 11 (
26 > 24) and setsrightIndex = 10. On the next pass the range is[2 ... 22], butvalueDelta(22) is larger thanrangeDelta(20), so the interpolated index isfloor(22 * 10 / 20) = 11, which is beyondrightIndex.sortedArray[11]is still> 24, sorightIndex = 11 - 1 = 10again, and the loop repeats forever.Fix: the function already returns
-1when the seek element is below the range (valueDelta < 0). This adds the symmetric check for a seek element above the range maximum (seekElement > sortedArray[rightIndex]), which also guaranteesvalueDelta <= rangeDelta, so the interpolated index always stays inside[leftIndex, rightIndex]and every iteration shrinks the range.Tests
should not loop forever when the seek element is above part of the rangecovers the reported input plus two similar missing-element cases. It hangs onmasterand passes with the fix.npm run lintclean.Fixes #2219