Pick a kid, split the room

Quick Sort

The analogy

Point at one kid — the pivot. Everyone shorter shuffles to their left, everyone taller to their right. That pivot is now in their final spot forever, and you repeat on each side. Fast when your pivot lands near the middle; slow if you keep picking the tallest.

Visualizer

Watch the room split

step 1 / 33
5
3
8
1
9
2
7
4

8 numbers, out of order. Press play — or step through one comparison at a time.

def quick_sort(a, lo=0, hi=None):
    hi = len(a) - 1 if hi is None else hi
    if lo >= hi:
        return a
    p = partition(a, lo, hi)
    quick_sort(a, lo, p - 1)
    quick_sort(a, p + 1, hi)
    return a

def partition(a, lo, hi):
    pivot, i = a[hi], lo
    for j in range(lo, hi):
        if a[j] < pivot:
            a[i], a[j] = a[j], a[i]
            i += 1
    a[i], a[hi] = a[hi], a[i]
    return i
Check yourself

After one partition, what is guaranteed?