"""Heap sort.

Idea
----
Rearrange the array into a max-heap (every parent >= its children). The
largest value is then at index 0: swap it to the end, shrink the heap by one
and "sift down" the new root to restore the heap property. Repeat.

Building the heap bottom-up with sift-down costs O(n) total, not O(n log n).

Complexity
----------
Time:  O(n log n) in every case
Space: O(1) extra (in place). Not stable.

When to use
-----------
When you need an in-place sort with a guaranteed O(n log n) bound. It is also
the clearest way to learn how a binary heap works.
"""

from typing import MutableSequence, TypeVar

T = TypeVar("T")


def _sift_down(items: MutableSequence[T], root: int, size: int) -> None:
    while True:
        largest = root
        left, right = 2 * root + 1, 2 * root + 2
        if left < size and items[left] > items[largest]:  # type: ignore[operator]
            largest = left
        if right < size and items[right] > items[largest]:  # type: ignore[operator]
            largest = right
        if largest == root:
            return
        items[root], items[largest] = items[largest], items[root]
        root = largest


def heap_sort(items: MutableSequence[T]) -> MutableSequence[T]:
    """Sort ``items`` in place and return it."""
    n = len(items)
    for root in range(n // 2 - 1, -1, -1):
        _sift_down(items, root, n)
    for end in range(n - 1, 0, -1):
        items[0], items[end] = items[end], items[0]
        _sift_down(items, 0, end)
    return items
