@jollie/binary-search
v1.0.8
Published
Binary search: Equal & closest search in sorted array.
Downloads
1
Readme
Binary search
Equal or closest search in sorted array using binary search algorithm.
See https://en.wikipedia.org/wiki/Binary_search_algorithm#Procedure
Performance
Binary search is faster than linear search (except for small array ...).
Install
yarn add @jollie/binary-search
or
npm install @jollie/binary-search
Usage
import { equalSearch, closestSearch } from '@jollie/binary-search';
// Equal search in numeric array
equalSearch([1, 2, 3], 2); // Found -> Output 1
equalSearch([1, 2, 3], 5); // Not found -> Output -1
// Equal search in string array
equalSearch(['a', 'b', 'c'], 'c'); // Found -> Output 2
equalSearch(['a', 'b', 'c'], '?'); // Not found -> Output -1
// Closest search
closestSearch([1, 2, 3], 2.2); // Output 1
closestSearch([1, 2, 3], 2.6); // Output 2
closestSearch([1, 2, 3], -1); // Output 0
closestSearch([1, 2, 3], 1000); // Output 2
Params
equalSearch(haystack, needle[, { compare, from, to }]);
closestSearch(haystack, needle[, { compare, from, to }]);
| Prop | Type | Default | Note |
|:-----------|:------------|:-------------------------------------|:------|
| haystack
| array
| mandatory | Array of values
| needle
| any
| mandatory | Searched value
| compare
| function
| (needle, value) => needle - value
| Compare function. Special case for equalSearch:if needle is a string, default compare is(a, b) => a.localeCompare(b)
| from
| integer
| 0
| Start index for range searching
| to
| integer
| haystack.length - 1
| End index for range searching
Return value
Index in the array or -1 if not found
Exception
Throw RangerError if from
or to
are outbounds