Function exponentialSearch

  • Performs an exponential search on an array using a custom comparison function.

    • If isSorted is false, the array will first be sorted using TimSort.
    • Uses exponential search to quickly narrow down the range, followed by binary search within the identified range.

    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: ExponentialSearchConfig<T>

      Configuration object containing:

      • compareFn: Comparison function defining the element 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 = [5, 2, 9, 1];
    const config = { compareFn: (a, b) => a - b, isSorted: false };
    const index = exponentialSearch(data, 9, 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 = exponentialSearch(data, 'banana', config);
    // index would be 1