From 963b227fe23b2f13e67a410137595e96abe59b17 Mon Sep 17 00:00:00 2001 From: Darkslayer3324j Date: Sat, 19 Sep 2026 21:51:47 +0500 Subject: [PATCH] Fix interpolationSearch looping forever when the seek element is above 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 --- .../__test__/interpolationSearch.test.js | 7 +++++++ .../search/interpolation-search/interpolationSearch.js | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/src/algorithms/search/interpolation-search/__test__/interpolationSearch.test.js b/src/algorithms/search/interpolation-search/__test__/interpolationSearch.test.js index 7ddc548b63..6bd1f5103c 100644 --- a/src/algorithms/search/interpolation-search/__test__/interpolationSearch.test.js +++ b/src/algorithms/search/interpolation-search/__test__/interpolationSearch.test.js @@ -21,4 +21,11 @@ describe('interpolationSearch', () => { expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 19000], 800)).toBe(4); expect(interpolationSearch([0, 10, 11, 12, 13, 14, 15], 10)).toBe(1); }); + + it('should not loop forever when the seek element is missing and above part of the range', () => { + expect(interpolationSearch([2, 4, 8, 8, 10, 12, 18, 20, 20, 20, 22, 26, 26, 28], 24)).toBe(-1); + expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 1900], 1500)).toBe(-1); + expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 1900], 2000)).toBe(-1); + expect(interpolationSearch([1, 2, 3], 5)).toBe(-1); + }); }); diff --git a/src/algorithms/search/interpolation-search/interpolationSearch.js b/src/algorithms/search/interpolation-search/interpolationSearch.js index 8546c5be3b..cf939f3721 100644 --- a/src/algorithms/search/interpolation-search/interpolationSearch.js +++ b/src/algorithms/search/interpolation-search/interpolationSearch.js @@ -21,6 +21,14 @@ export default function interpolationSearch(sortedArray, seekElement) { return -1; } + // If the seek element is higher than the highest element of the range then + // there is nothing to find either. Without this check the interpolated + // middle index can land beyond rightIndex, "rightIndex = middleIndex - 1" + // then does not shrink the range and the loop never ends. + if (seekElement > sortedArray[rightIndex]) { + return -1; + } + // If range delta is zero then subarray contains all the same numbers // and thus there is nothing to search for unless this range is all // consists of seek number.