"""Week 4: Elementary sorts. All return a new sorted list and leave the input untouched."""
from __future__ import annotations

from typing import List


def bubble_sort(items: List[int]) -> List[int]:
    """O(n^2), stable, stops early when a pass makes no swaps (O(n) on sorted input)."""
    a = list(items)
    for end in range(len(a) - 1, 0, -1):
        swapped = False
        for i in range(end):
            if a[i] > a[i + 1]:
                a[i], a[i + 1] = a[i + 1], a[i]
                swapped = True
        if not swapped:
            break
    return a


def selection_sort(items: List[int]) -> List[int]:
    """O(n^2) always, not stable, at most n - 1 swaps."""
    a = list(items)
    for i in range(len(a)):
        smallest = min(range(i, len(a)), key=a.__getitem__)
        a[i], a[smallest] = a[smallest], a[i]
    return a


def insertion_sort(items: List[int]) -> List[int]:
    """O(n^2) worst, O(n) on nearly sorted input, stable."""
    a = list(items)
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key
    return a


def cyclic_sort(items: List[int]) -> List[int]:
    """For a permutation of 1..n: put value v at index v - 1. O(n) time, O(1) extra space."""
    a = list(items)
    i = 0
    while i < len(a):
        j = a[i] - 1
        if a[i] != a[j]:
            a[i], a[j] = a[j], a[i]
        else:
            i += 1
    return a
