Path: blob/master/node_modules/@adiwajshing/keyed-db/lib/BinarySearch.js
1126 views
"use strict";1Object.defineProperty(exports, "__esModule", { value: true });2/**3* Binary search4* @param array the array to search in5* @param predicate return a value of < 0, if the item you're looking for should come before, 0 if it is the item you're looking for6*/7function binarySearch(array, predicate) {8let low = 0;9let high = array.length;10// base cases to allow entering a sorted collection in O(N)11if (array.length === 0)12return low;13if (predicate(array[low]) < 0)14return low - 1;15else if (predicate(array[low]) === 0)16return low;17const maxPred = predicate(array[high - 1]);18if (maxPred > 0)19return high;20else if (maxPred === 0)21return high - 1;22while (low !== high) {23const mid = low + Math.floor((high - low) / 2);24const pred = predicate(array[mid]);25if (pred < 0)26high = mid;27else if (pred > 0)28low = mid + 1;29else30return mid;31}32return low;33}34exports.default = binarySearch;353637