Function binarySearch

  • Category

    Perform a binary search to find an element in a sorted array.

    Time complexity: O(log n)

    Space complexity: O(1)

    Type Parameters

    • T

    Parameters

    • array: ArrayLike<T>

      Sorted array to perform binary search on

    • directionFn: DirectionFn<T>

      The function used to determine what direction to continue searching

    Returns ReturnType<T[]["find"]>

    The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

    Array

    const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    function directionFn(value: number) {
    const squared = value ** 2;

    if (squared === 64) {
    return 0;
    }

    return squared - 64;
    }

    binarySearch(array, directionFn);