Function ternarySearch

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

    • Ternary search divides the array into three segments for efficient searching.
    • If isSorted is false, the array will first be sorted using TimSort.
    • The search operates recursively, refining the search range into thirds.

    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 target element to find within the array.

    • Optionalleft: number = 0

      The left index of the current search range.

    • Optionalright: number = ...

      The right index of the current search range.

    • config: TernarySearchConfig<T>

      Configuration object containing:

      • compareFn: Comparison function defining the element order.
      • isSorted: Whether the data array is pre-sorted (defaults to false).

    Returns number

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

    // Using ternary search on a numeric array
    const data = [3, 5, 7, 9, 11];
    const config = { compareFn: (a, b) => a - b, isSorted: true };
    const index = ternarySearch(data, 9, 0, data.length - 1, config);
    // index would be 3
    // Using ternary search on an unsorted string array
    const data = ['banana', 'apple', 'cherry'];
    const config = { compareFn: (a, b) => a.localeCompare(b), isSorted: false };
    const index = ternarySearch(data, 'apple', 0, data.length - 1, config);
    // index would be 0 after sorting