Skip to content

closest does too many comparisons #4

@rocketraman

Description

@rocketraman

I haven't closely examined the reason why, but in some very basic testing, there were more comparisons than there should have been for an efficient binary search of the closest value. For example, the search:

bs.closest([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4, function(value, find) {
  console.log(`Comparing value ${value} with target ${find}`)
  if(value > find) return 1
  else if(value < find) return -1
  return 0
}) 

outputs:

Comparing value 4 with target 4
Comparing value 2 with target 4
Comparing value 3 with target 4
Comparing value 4 with target 4

One option that probably should be supported is to tell the search algorithm that there are no duplicated values so there is no extra work to find the first matching value. That would reduce the comparison count to 1 in the above search.

But even accounting for possible duplicates, there is still an extra comparison.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions