Function hybridSearch

  • Hybrid search that adapts to the data length and configuration for optimal performance.

    • For small datasets (less than linearSearchThreshold), linear search is used.
    • For mid-sized datasets (between linearSearchThreshold and binarySearchThreshold), binary search is applied.
    • For large datasets (greater than or equal to binarySearchThreshold), a Red-Black Tree is constructed, and the search is performed within the tree.

    Type Parameters

    • T

      The type of elements in the array.

    Parameters

    • data: T[]

      The array of data in which to search for the target.

    • target: T

      The target element to search for within the data array.

    • config: HybridSearchConfig<T>

      Configuration for the hybrid search algorithm, which includes:

      • linearSearchThreshold: Length threshold for linear search (default: 100).
      • binarySearchThreshold: Length threshold for binary search (default: 10000).
      • isSorted: Whether the data array is already sorted (default: false).
      • compareFn: Comparison function defining the element order.

    Returns number | boolean

    • The index of the target in the array or -1 if not found (for array searches). For Red-Black Tree search, returns true if found, false if not.
    // Using hybrid search on a small dataset (linear search)
    const data = [3, 1, 4, 1, 5];
    const config = { compareFn: (a, b) => a - b };
    const index = hybridSearch(data, 4, config);
    // index would be 2
    // Using hybrid search on a large dataset (Red-Black Tree search)
    const largeData = Array.from({ length: 100000 }, (_, i) => i);
    const config = { compareFn: (a, b) => a - b, isSorted: true };
    const found = hybridSearch(largeData, 99999, config);
    // found would be true