"""Shell sort.

Idea
----
Insertion sort is slow because each element moves one slot at a time. Shell
sort first insertion-sorts elements that are ``gap`` apart, for a shrinking
sequence of gaps, so far-away elements jump into roughly the right region
early. The final pass with gap 1 is an ordinary insertion sort on an almost
sorted list, which is fast.

This version uses Ciura's empirically good gap sequence, extended by
multiplying by 2.25 for long inputs.

Complexity
----------
Time:  depends on the gap sequence; roughly O(n^1.3) in practice with these
       gaps, and no tight bound is known. O(n log n) best case.
Space: O(1) extra. Not stable.

When to use
-----------
Embedded or memory-constrained code that needs something much faster than
insertion sort without recursion or extra memory.
"""

from typing import MutableSequence, TypeVar

T = TypeVar("T")

CIURA_GAPS = [701, 301, 132, 57, 23, 10, 4, 1]


def _gaps(n: int) -> list[int]:
    gaps = CIURA_GAPS[:]
    while gaps[0] * 2.25 < n:
        gaps.insert(0, int(gaps[0] * 2.25))
    return [g for g in gaps if g < n] or [1]


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