@onesy/algorithms
Version:
21 lines (20 loc) • 998 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@onesy/utils");
function binarySearchRecursive(array, value, startValue, endValue, options = {}) {
let start = startValue;
let end = endValue;
if (startValue === undefined && endValue === undefined) {
start = 0;
end = array.length - 1;
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);
}
if (end <= start && array[start] !== value)
return -1;
const middle = start + Math.floor((end - start) / 2);
if (array[middle] === value)
return middle;
return value < array[middle] ? binarySearchRecursive(array, value, start, middle - 1, options) : binarySearchRecursive(array, value, middle + 1, end, options);
}
exports.default = binarySearchRecursive;