@jollie/binary-search

1.0.8 • Public • Published

Version Licence Build Coverage Downloads

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 ...).

js-perf

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

Readme

Keywords

Package Sidebar

Install

npm i @jollie/binary-search

Weekly Downloads

0

Version

1.0.8

License

MIT

Unpacked Size

7.12 kB

Total Files

4

Last publish

Collaborators

  • thejellyfish