Skip to content

Fix interpolationSearch looping forever when the seek element is above part of the range - #2219

Open
Darkslayer3324j wants to merge 1 commit into
trekhleb:masterfrom
Darkslayer3324j:fix/interpolation-search-infinite-loop
Open

Darkslayer3324j wants to merge 1 commit into
trekhleb:masterfrom
Darkslayer3324j:fix/interpolation-search-infinite-loop

Conversation

@Darkslayer3324j

Copy link
Copy Markdown

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.

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.

Found by differential fuzzing (comparing 25+ algorithms in src/algorithms against simple reference implementations on random inputs); the fuzzer stopped on this input because it never finished. I added tests for the hanging input and a few similar ones (missing elements between and above existing values); npx jest src/algorithms/search and eslint pass.

Written with AI assistance (Claude Code); I reproduced the hang, traced the cause above, and ran the tests and linter.

…e part of the range

If the seek element is missing and larger than the highest element of the
current range, the interpolated middle index lands beyond rightIndex, so
rightIndex = middleIndex - 1 never shrinks the range. Return -1 when the seek
element exceeds the range maximum, and add tests.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
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