1.0.8 • Published 3 years ago

@jollie/binary-search v1.0.8

Weekly downloads
1
License
MIT
Repository
github
Last release
3 years ago

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 }]);
PropTypeDefaultNote
haystackarraymandatoryArray of values
needleanymandatorySearched value
comparefunction(needle, value) => needle - valueCompare function. Special case for equalSearch:if needle is a string, default compare is(a, b) => a.localeCompare(b)
frominteger0Start index for range searching
tointegerhaystack.length - 1End index for range searching

Return value

Index in the array or -1 if not found

Exception

Throw RangerError if from or to are outbounds