Function heapSort

  • Sorts an array using the HeapSort algorithm.

    • Converts the array into a max-heap or min-heap based on the compareFn.
    • Repeatedly extracts the root of the heap to produce a sorted array.

    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 sort 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, in-place.

    // Basic usage with numbers
    const arr = [3, 9, 2, 1, 4, 5];
    const sortedArr = heapSort(arr, (a, b) => a - b);
    console.log(sortedArr); // [1, 2, 3, 4, 5, 9]
    // Usage with strings
    const arr = ['banana', 'apple', 'cherry'];
    const sortedArr = heapSort(arr, (a, b) => a.localeCompare(b));
    console.log(sortedArr); // ['apple', 'banana', 'cherry']