UNPKG

@onesy/algorithms

Version:
21 lines (20 loc) 769 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("@onesy/utils"); function binarySearch(array, value, options = {}) { if (options === null || options === void 0 ? void 0 : options.sort) array.sort((0, utils_1.is)('function', options === null || options === void 0 ? void 0 : options.sortMethod) ? options.sortMethod : (a, b) => a - b); let start = 0; let end = array.length - 1; while (start <= end) { const middle = start + Math.floor((end - start) / 2); if (array[middle] === value) return middle; if (value < array[middle]) end = middle - 1; else start = middle + 1; } return -1; } exports.default = binarySearch;