JSPM

array-binsearch

1.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 685
  • Score
    100M100P100Q111876F
  • License Apache-2.0

Binary search a sorted array

Package Exports

  • array-binsearch

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (array-binsearch) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

array-binsearch

A library for performing a binary search on an array with insertion support.

Supports typescript usage and rollup.

Example

Basic

var binsearch = require("./index").default;
var sortedSet = [2, 4, 6, 8, 9, 11];

function add(set, val) {
  var i = binsearch(set, val);
  if (i < 0) {
    i = ~i;
    set.splice(i, 0, val);
  }
}

add(sortedSet, 4);
add(sortedSet, 3);
add(sortedSet, 8);
add(sortedSet, 20);
add(sortedSet, -1);

console.log(sortedSet);

// => [ -1, 2, 3, 4, 6, 8, 9, 11, 20 ]

With Comparator

var binsearch = require("./index").default;
var sortedSet = [2, 4, 6, 8, 9, 11];
function comparator(a, b) {
  return a - b;
}

function add(set, val) {
  var i = binsearch(set, val);
  if (i < 0) {
    i = ~i;
    set.splice(i, 0, val);
  }
}

add(sortedSet, 4);
add(sortedSet, 3);
add(sortedSet, 8);
add(sortedSet, 20);
add(sortedSet, -1);

console.log(sortedSet);

// => [ -1, 2, 3, 4, 6, 8, 9, 11, 20 ]