Skip to content

fix(interpolation-search): avoid infinite loop when seek element exceeds range - #2226

Open
xingzihai wants to merge 1 commit into
trekhleb:masterfrom
xingzihai:fix/issue-2219
Open

xingzihai wants to merge 1 commit into
trekhleb:masterfrom
xingzihai:fix/issue-2219

Conversation

@xingzihai

Copy link
Copy Markdown

Description

interpolationSearch never returns for some inputs where the seek element is missing:

interpolationSearch([2, 4, 8, 8, 10, 12, 18, 20, 20, 20, 22, 26, 26, 28], 24); // hangs

Trace: the first pass interpolates index 11 (26 > 24) and sets rightIndex = 10. On the next pass the range is [2 ... 22], but valueDelta (22) is larger than rangeDelta (20), so the interpolated index is floor(22 * 10 / 20) = 11, which is beyond rightIndex. sortedArray[11] is still > 24, so rightIndex = 11 - 1 = 10 again, and the loop repeats forever.

Fix: the function already returns -1 when 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 guarantees valueDelta <= rangeDelta, so the interpolated index always stays inside [leftIndex, rightIndex] and every iteration shrinks the range.

Tests

  • New test should not loop forever when the seek element is above part of the range covers the reported input plus two similar missing-element cases. It hangs on master and passes with the fix.
  • Full suite: 178 suites / 588 tests pass; npm run lint clean.

Fixes #2219

…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant