"""Insertion sort.

Idea
----
Grow a sorted prefix one element at a time. Take the next value, shift every
larger value in the prefix one slot to the right, and drop the value into the
gap. This is how most people sort a hand of playing cards.

Complexity
----------
Time:  O(n^2) worst/average, O(n) best (already or nearly sorted input)
Space: O(1) extra. Stable.

When to use
-----------
Small or nearly sorted arrays. Real-world hybrids such as Timsort use
insertion sort on short runs because its constant factor is tiny.
"""

from typing import MutableSequence, TypeVar

T = TypeVar("T")


def insertion_sort(items: MutableSequence[T]) -> MutableSequence[T]:
    """Sort ``items`` in place and return it."""
    for i in range(1, len(items)):
        value = items[i]
        j = i - 1
        while j >= 0 and items[j] > value:  # type: ignore[operator]
            items[j + 1] = items[j]
            j -= 1
        items[j + 1] = value
    return items
