Function binarySearch

Performs binary search on a sorted array. Returns the index of the element if found, or a negative index indicating where it should be inserted.

binarySearch((x: number) => x - 5)([1, 3, 5, 7, 9]);
// => 2 (index of 5)

binarySearch((x: number) => x - 4)([1, 3, 5, 7, 9]);
// => -3 (should be inserted at index 2)
  • Type Parameters

    • T extends readonly unknown[]

      Element type

    Parameters

    • compare: (element: unknown) => number

      Comparison function returning 0 for match, negative if target is less, positive if greater

    Returns (array: T) => number

    Index of element if found, or negative index of insertion point - 1