Function mergeSort

  • Sorts an array using the Merge Sort algorithm.

    • Recursively divides the array into halves, sorts each half, and merges them.

    Type Parameters

    • T

      The type of elements in the array.

    Parameters

    • arr: T[]

      The array to be sorted.

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

      A comparison function that defines the sorting order. Should return a positive number if a > b, 0 if a === b, and a negative number if a < b.

        • (a, b): number
        • Parameters

          Returns number

    Returns T[]

    The sorted array.

    // Sorting an array of numbers
    const arr = [3, 1, 4, 1, 5];
    const sortedArr = mergeSort(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 = mergeSort(arr, (a, b) => a.localeCompare(b));
    console.log(sortedArr); // ['apple', 'banana', 'cherry']