Heapsort is in place, and $O(n\log n)$. It uses a (binary) heap to manage the sorting.

Heap

Heap is an array object that can be viewed as a nearly complete binary tree.

Screenshot 2024-09-19 at 10.07.36 AM.png

Screenshot 2024-09-19 at 10.07.44 AM.png

A heap array object has two attributes

Heap structure (given index $i$)

Building a Max-Heap

To build a max-heap, we first need to understand heapify. Max-heapify is to swap the smaller number downward the heap.

Max-Heapify

Runtime: $O(\log n)$

const max_heapify = (A, i) => {
    let l = 2 * i + 1;  // Left child
    let r = 2 * i + 2;  // Right child
    let largest = i;

    if (l < A.heapsize && A[l] > A[largest])
        largest = l;
    
    if (r < A.heapsize && A[r] > A[largest])
        largest = r;
    
    if (largest !== i) {
        [A[i], A[largest]] = [A[largest], A[i]];  // Swap
        max_heapify(A, largest);
    }
};

Build Max-Heap