Sorts an array using the HeapSort algorithm.
compareFn
The type of elements in the array.
The array to be sorted.
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
a === b
a < b
The sorted array, in-place.
// Basic usage with numbersconst arr = [3, 9, 2, 1, 4, 5];const sortedArr = heapSort(arr, (a, b) => a - b);console.log(sortedArr); // [1, 2, 3, 4, 5, 9] Copy
// Basic usage with numbersconst 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 stringsconst arr = ['banana', 'apple', 'cherry'];const sortedArr = heapSort(arr, (a, b) => a.localeCompare(b));console.log(sortedArr); // ['apple', 'banana', 'cherry'] Copy
// Usage with stringsconst arr = ['banana', 'apple', 'cherry'];const sortedArr = heapSort(arr, (a, b) => a.localeCompare(b));console.log(sortedArr); // ['apple', 'banana', 'cherry']
Sorts an array using the HeapSort algorithm.
compareFn
.