"""Quick sort (in place, Lomuto partition, random pivot).

Idea
----
Pick a pivot, then partition the list so every value smaller than the pivot
sits to its left and every other value to its right. The pivot is now in its
final position; recurse on both sides. A random pivot makes the O(n^2) worst
case vanishingly unlikely on any fixed input (for example sorted data).

Complexity
----------
Time:  O(n log n) expected, O(n^2) worst case
Space: O(log n): we keep working on the smaller side and push the larger
       side onto an explicit stack, so the stack never holds more than
       O(log n) ranges. Not stable.

When to use
-----------
General-purpose in-memory sorting where stability is not needed. Very cache
friendly, which is why tuned variants are popular in standard libraries.
"""

import random
from typing import MutableSequence, TypeVar

T = TypeVar("T")


def partition(items: MutableSequence[T], low: int, high: int) -> int:
    """Lomuto partition of ``items[low:high + 1]`` around a random pivot.

    Returns the final index of the pivot.
    """
    pivot_index = random.randint(low, high)
    items[pivot_index], items[high] = items[high], items[pivot_index]
    pivot = items[high]
    store = low
    for i in range(low, high):
        if items[i] < pivot:  # type: ignore[operator]
            items[i], items[store] = items[store], items[i]
            store += 1
    items[store], items[high] = items[high], items[store]
    return store


def quick_sort(items: MutableSequence[T]) -> MutableSequence[T]:
    """Sort ``items`` in place and return it."""
    low, high = 0, len(items) - 1
    stack = [(low, high)]
    while stack:
        low, high = stack.pop()
        while low < high:
            p = partition(items, low, high)
            # Defer the larger side and keep working on the smaller one.
            if p - low < high - p:
                stack.append((p + 1, high))
                high = p - 1
            else:
                stack.append((low, p - 1))
                low = p + 1
    return items
