"""Bubble sort.

Idea
----
Walk through the list and swap neighbours that are out of order. After each
pass the largest remaining value has "bubbled" to the end, so the unsorted
region shrinks by one. If a pass makes no swaps the list is already sorted and
we can stop early.

Complexity
----------
Time:  O(n^2) worst/average, O(n) best (already sorted, thanks to early exit)
Space: O(1) extra (in place). Stable.

When to use
-----------
Almost never in production. It is useful for teaching swaps, invariants and
the idea of an early-exit optimisation.
"""

from typing import MutableSequence, TypeVar

T = TypeVar("T")


def bubble_sort(items: MutableSequence[T]) -> MutableSequence[T]:
    """Sort ``items`` in place and return it."""
    n = len(items)
    for end in range(n - 1, 0, -1):
        swapped = False
        for i in range(end):
            if items[i] > items[i + 1]:  # type: ignore[operator]
                items[i], items[i + 1] = items[i + 1], items[i]
                swapped = True
        if not swapped:
            break
    return items
