UNPKG

@onesy/algorithms

Version:
13 lines 554 B
import { is } from '@onesy/utils'; export default function binarySearch(array, value) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (options?.sort) array.sort(is('function', 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; }