Function timSort

  • Sorts an array using the Hybrid TimSort algorithm with adaptive run detection and memory optimization.

    • Utilizes a combination of merge sort and insertion sort.

    Type Parameters

    • T

      The type of elements in the array.

    Parameters

    • arr: T[]

      The array to be sorted.

    • compareFn: ((a: T, b: T) => number)

      Comparison function to determine sort order.

        • (a, b): number
        • Parameters

          Returns number

    • Optionalconfig: HybridTimSortConfig = {}

      Configuration options, such as minGallop and minRunLength.

    Returns T[]

    The sorted array.

    // Sorting an array of numbers
    const arr = [3, 1, 4, 1, 5];
    const sortedArr = timSort(arr, (a, b) => a - b);
    console.log(sortedArr); // [1, 1, 3, 4, 5]
    // Sorting an array of strings
    const arr = ['banana', 'apple', 'cherry'];
    const sortedArr = timSort(arr, (a, b) => a.localeCompare(b));
    console.log(sortedArr); // ['apple', 'banana', 'cherry']