Binary search

Implementation of a search algorithm on a sorted array which looks up for the specified value by repeatedly dividing the search interval in half.

binarySearch()

/**
 * Finds item in sorted array greater than or equal to the specified target.
 *
 * @param arr Array to search in.
 * @param target Search target.
 * @param from Index to start search from (inclusive). Will start from 0 by default.
 * @param to Index to stop search at (exclusive). Will examine the whole array by default.
 * @param compare Comparison function. Items are compared as numbers by default.
 * @returns Object with 'index' field representing an item the search has stopped at
 * and 'exact' field telling whether the target was matched exactly.
 */
function binarySearch<T, K = T>(
  arr: T[],
  target: K,
  from?: number,
  to?: number,
  compare: CompareFunc<T, K> = compareAsNumbers,
): { index: number, exact: boolean };

Finds item in sorted array greater than or equal to the specified target.

Last updated

Was this helpful?