diff --git a/Search/InterpolationSearch.js b/Search/InterpolationSearch.js index 93f3b78b0e..47e10179ef 100644 --- a/Search/InterpolationSearch.js +++ b/Search/InterpolationSearch.js @@ -18,6 +18,11 @@ export function interpolationSearch(arr, key) { // Because the array is sorted the key must be between low and high while (low <= high && key >= arr[low] && key <= arr[high]) { + // Equal endpoints mean every remaining element matches the key. + if (arr[low] === arr[high]) { + return low + } + delta = (key - arr[low]) / (arr[high] - arr[low]) position = low + Math.floor((high - low) * delta) diff --git a/Search/test/InterpolationSearch.test.js b/Search/test/InterpolationSearch.test.js index 674c059db2..c4b2ce8588 100644 --- a/Search/test/InterpolationSearch.test.js +++ b/Search/test/InterpolationSearch.test.js @@ -1,5 +1,17 @@ import { interpolationSearch } from '../InterpolationSearch' +test.each([ + [[7], 7, 0], + [[7, 7, 7], 7, 0], + [[-4, -4, -4], -4, 0], + [[0, 0], 0, 0], + [[7], 6, -1], + [[7, 7, 7], 8, -1], + [[], 7, -1] +])('interpolationSearch(%j, %s) => %s', (array, key, expected) => { + expect(interpolationSearch(array, key)).toBe(expected) +}) + test('interpolationSearch([2, 6, 8, 14, 122, 169], 144) => -1', () => { const array = [2, 6, 8, 14, 122, 169] const key = 144