Function binarySearch

  • Performs a binary search on an array with a custom comparison function.

    • If isSorted is false, the array will be sorted using TimSort.
    • Assumes that the array (or sorted copy) contains comparable elements as per the specified compareFn.

    Type Parameters

    • T

      The type of elements in the array.

    Parameters

    • data: T[]

      The array in which to search for the target.

    • target: T

      The element to search for within the array.

    • config: BinarySearchConfig<T>

      Configuration object, which includes:

      • compareFn: A comparison function to determine the order.
      • isSorted: Whether the array is pre-sorted (defaults to false).

    Returns number

    The index of the target in the array, or -1 if not found.

    // Basic usage with an array of numbers
    const data = [4, 2, 7, 1];
    const config = { compareFn: (a, b) => a - b, isSorted: false };
    const index = binarySearch(data, 7, config);
    // index would be 3 after sorting
    // Usage with strings in alphabetical order
    const data = ['apple', 'banana', 'cherry'];
    const config = { compareFn: (a, b) => a.localeCompare(b), isSorted: true };
    const index = binarySearch(data, 'banana', config);
    // index would be 1