Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add interpolation search tests #133

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/algorithms/search/interpolation_search.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
10 changes: 9 additions & 1 deletion test/algorithms/search/testInterpolationSearch.js
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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);
});
Expand Down