The heap sort algorithm
We can use the binary heap data structure to help us create a very famous sorting algorithm: the heap sort. The heap sort algorithm consists of three steps:
- Create a max heap using the array to be sorted as the source.
- After creating the max heap, the largest value will be stored in the first index of the heap. We will replace the first value with the last value of the heap, decreasing the size of the heap by
1
. - Finally, we
heapify
(sift down) the root of the heap and repeat step 2 until the size of the heap is equal to1
.
We use the max heap results in an array sorted in ascending order (from smallest to biggest). If we want the array to be sorted in descending order, we can use the min heap instead.
The following is the code for the heap sort algorithm:
function heapSort(array, compareFn = defaultCompare) { let heapSize = array.length; buildMaxHeap(array, compareFn); // step 1 while (heapSize > 1) { swap(array, 0, --heapSize); // step 2 heapify(array...