From fb9ca3470da81cc365b3df8112c7841fa8503fc0 Mon Sep 17 00:00:00 2001 From: jonatan Date: Sat, 5 Mar 2022 16:12:07 +0200 Subject: [PATCH 1/2] bug(interpolation search): add floor for the division --- src/algorithms/search/interpolation_search.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/algorithms/search/interpolation_search.js b/src/algorithms/search/interpolation_search.js index 426c1c6e..d131bc6a 100644 --- a/src/algorithms/search/interpolation_search.js +++ b/src/algorithms/search/interpolation_search.js @@ -8,12 +8,16 @@ const interpolationsearch = (sortedArray, element) => { let left = 0; let right = sortedArray.length - 1; - while ((left <= right) && (element >= sortedArray[left]) && (element <= sortedArray[right])) { + while ( + left <= right && + element >= sortedArray[left] && + element <= sortedArray[right] + ) { const valDiff = sortedArray[right] - sortedArray[left]; const posDiff = right - left; const elementDiff = element - sortedArray[left]; - const pos = left + ((posDiff * elementDiff) / valDiff || 0); + const pos = left + (Math.floor((posDiff * elementDiff) / valDiff) || 0); if (sortedArray[pos] === element) { return pos; From faa3e1045695cc30311569defd17b7ab7c921f21 Mon Sep 17 00:00:00 2001 From: jonatan Date: Sat, 5 Mar 2022 16:12:32 +0200 Subject: [PATCH 2/2] test(interpolation search): test coverage 100% --- test/algorithms/search/testInterpolationSearch.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/test/algorithms/search/testInterpolationSearch.js b/test/algorithms/search/testInterpolationSearch.js index f3f0c514..5143df30 100644 --- a/test/algorithms/search/testInterpolationSearch.js +++ b/test/algorithms/search/testInterpolationSearch.js @@ -1,5 +1,6 @@ /* eslint-env mocha */ -const interpolationsearch = require('../../../src').algorithms.search.interpolationsearch; +const interpolationsearch = + require('../../../src').algorithms.search.interpolationsearch; const assert = require('assert'); describe('Interpolation Search', () => { @@ -47,8 +48,15 @@ describe('Interpolation Search', () => { assert.equal(interpolationsearch(sortedArray, 48), 24); }); + it('should check for edge case where element at pos > element to search', () => { + const sortedArray = [1, 3, 5, 14, 21, 25, 26, 27]; + + assert.equal(interpolationsearch(sortedArray, 25), 5); + }); + it('should check for edge case where array contains all duplicate values', () => { const duplicateArray = [42, 42, 42, 42]; + assert.equal(interpolationsearch(duplicateArray, 6), -1); assert.equal(interpolationsearch(duplicateArray, 42), 0); });