trekhleb / trekhleb/javascript-algorithms

interpolationSearch may not return the first index with the value

Open
#306 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
197k
Forks
31k
PR merge metrics
No merged PRs in 30d

Description

Details:

Behaviour of interpolationSearch may be considered inconsistent.
For some arrays it will return the index of the first match - expect(interpolationSearch([1, 1], 1)).toBe(0) - while for others it returns the second or third one.

Step to reproduce: interpolationSearch([-1, 0, 0], 0))
Expected result: 1
Got: 2

How did I find it?

Thanks to property based testing framework fast-check.
The property was the following:

import fc from 'fast-check';

fc.assert(
  fc.property(
    fc.array(fc.integer()).map(arr => [...arr].sort((a, b) => a - b)),
    fc.integer(),
    (arr, i) => expect(interpolationSearch(arr, i)).toBe(arr.indexOf(i))
  )
)

Or:

for any arr - sorted array of integers - and i - integer value
interpolationSearch(arr, i) should be equivalent to arr.indexOf(i)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Locate the JavaScript implementation and existing tests for interpolationSearch, then reproduce the [-1, 0, 0] case and compare its result with Array.indexOf. Add regression coverage for duplicate values and ensure the search returns the first matching index for sorted integer arrays.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
search
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.