"""Week 5: Divide and conquer sorts and non-comparison sorts."""
from __future__ import annotations

import random
from typing import List


def merge_sort(items: List[int]) -> List[int]:
    """O(n log n) always, stable, O(n) extra space."""
    if len(items) <= 1:
        return list(items)
    mid = len(items) // 2
    left, right = merge_sort(items[:mid]), merge_sort(items[mid:])
    merged, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            merged.append(left[i])
            i += 1
        else:
            merged.append(right[j])
            j += 1
    merged.extend(left[i:])
    merged.extend(right[j:])
    return merged


def count_inversions(items: List[int]) -> int:
    """Pairs i < j with items[i] > items[j], counted during merge sort in O(n log n)."""

    def sort_count(a: List[int]):
        if len(a) <= 1:
            return a, 0
        mid = len(a) // 2
        left, x = sort_count(a[:mid])
        right, y = sort_count(a[mid:])
        merged, i, j, inv = [], 0, 0, x + y
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                merged.append(left[i])
                i += 1
            else:
                merged.append(right[j])
                inv += len(left) - i
                j += 1
        merged += left[i:] + right[j:]
        return merged, inv

    return sort_count(list(items))[1]


def quick_sort(items: List[int], seed: int | None = None) -> List[int]:
    """In-place Lomuto partition on a copy with a random pivot: O(n log n) expected."""
    a = list(items)
    rng = random.Random(seed)

    def partition(lo: int, hi: int) -> int:
        p = rng.randint(lo, hi)
        a[p], a[hi] = a[hi], a[p]
        pivot, store = a[hi], lo
        for i in range(lo, hi):
            if a[i] < pivot:
                a[i], a[store] = a[store], a[i]
                store += 1
        a[store], a[hi] = a[hi], a[store]
        return store

    stack = [(0, len(a) - 1)]
    while stack:
        lo, hi = stack.pop()
        if lo < hi:
            p = partition(lo, hi)
            stack.append((lo, p - 1))
            stack.append((p + 1, hi))
    return a


def quickselect(items: List[int], k: int, seed: int | None = None) -> int:
    """k-th smallest (0-based) in O(n) expected time using three-way partitioning."""
    if not 0 <= k < len(items):
        raise IndexError("k out of range")
    rng = random.Random(seed)
    a = list(items)
    while True:
        pivot = a[rng.randrange(len(a))]
        lows = [x for x in a if x < pivot]
        pivots = [x for x in a if x == pivot]
        if k < len(lows):
            a = lows
        elif k < len(lows) + len(pivots):
            return pivot
        else:
            k -= len(lows) + len(pivots)
            a = [x for x in a if x > pivot]


def counting_sort(items: List[int]) -> List[int]:
    """O(n + range) for integers; stable when rebuilt from prefix counts."""
    if not items:
        return []
    lo, hi = min(items), max(items)
    counts = [0] * (hi - lo + 1)
    for x in items:
        counts[x - lo] += 1
    for i in range(1, len(counts)):
        counts[i] += counts[i - 1]
    out = [0] * len(items)
    for x in reversed(items):
        counts[x - lo] -= 1
        out[counts[x - lo]] = x
    return out


def radix_sort(items: List[int]) -> List[int]:
    """LSD radix sort for non-negative integers, base 10."""
    if any(x < 0 for x in items):
        raise ValueError("radix_sort supports non-negative integers only")
    a = list(items)
    exp = 1
    while a and max(a) // exp > 0:
        buckets: List[List[int]] = [[] for _ in range(10)]
        for x in a:
            buckets[(x // exp) % 10].append(x)
        a = [x for b in buckets for x in b]
        exp *= 10
    return a
