"""Selection sort.

Idea
----
Repeatedly find the smallest value in the unsorted suffix and swap it into the
first unsorted position. The prefix ``items[:i]`` is always sorted and holds
the ``i`` smallest values.

Complexity
----------
Time:  O(n^2) in every case (it always scans the whole suffix)
Space: O(1) extra. Not stable (a long-distance swap can reorder equal keys).

When to use
-----------
When writes are expensive: selection sort performs at most n - 1 swaps.
"""

from typing import MutableSequence, TypeVar

T = TypeVar("T")


def selection_sort(items: MutableSequence[T]) -> MutableSequence[T]:
    """Sort ``items`` in place and return it."""
    n = len(items)
    for i in range(n - 1):
        smallest = i
        for j in range(i + 1, n):
            if items[j] < items[smallest]:  # type: ignore[operator]
                smallest = j
        if smallest != i:
            items[i], items[smallest] = items[smallest], items[i]
    return items
