"""Bucket sort (for floats spread over a known range).

Idea
----
Split the value range into n equal-width buckets, drop each value into its
bucket, sort each (small) bucket, and concatenate. If the input is spread
roughly uniformly, each bucket holds O(1) values and the whole thing runs in
linear expected time.

Complexity
----------
Time:  O(n) expected for uniformly distributed input, O(n^2) worst case
       (everything lands in one bucket and the per-bucket sort is quadratic;
       using ``sorted`` per bucket makes the worst case O(n log n))
Space: O(n)

When to use
-----------
Floating-point keys known to be spread fairly evenly, for example random
numbers in [0, 1) or percentages.
"""

from collections.abc import Sequence


def bucket_sort(values: Sequence[float]) -> list[float]:
    """Return a new sorted list."""
    n = len(values)
    if n <= 1:
        return list(values)
    lo, hi = min(values), max(values)
    if lo == hi:
        return list(values)
    width = (hi - lo) / n
    buckets: list[list[float]] = [[] for _ in range(n)]
    for v in values:
        index = min(int((v - lo) / width), n - 1)  # hi goes in the last bucket
        buckets[index].append(v)
    return [v for bucket in buckets for v in sorted(bucket)]
