1.0.6 • Published 4 years ago

@jellyfish-commuting/binary-search v1.0.6

Weekly downloads
2
License
MIT
Repository
github
Last release
4 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 @jellyfish-commuting/binary-search

or

npm install @jellyfish-commuting/binary-search

Usage

import { equalSearch, closestSearch } from '@jellyfish-commuting/binary-search';

 // Create an array [0...99]
const numbers = new Array(100).fill().map((nop, i) => i);

// Create an array ['a'...'z']
const letters = new Array(26).fill().map((nop, i) => String.fromCharCode(97 + i));

// Equal search in numeric array
equalSearch(numbers, 7);   // Found -> Output 7
equalSearch(numbers, 123); // Not found -> Output -1

// Equal search in string array
equalSearch(letters, 'h');         // Found -> Output 7
equalSearch(letters, 'jellyfish'); // Not found -> Output -1

// Closest search
closestSearch(numbers, 7.2);  // Output 7
closestSearch(numbers, -1);   // Output 0
closestSearch(numbers, 1000); // Output 99

Params

equalSearch(haystack, needle[, { compare, from, to }]);
closestSearch(haystack, needle[, { compare, from, to }]);
PropTypeDefaultNote
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

1.0.6

4 years ago

1.0.5

4 years ago