Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 72 / 101

Partition the possibility.

Split around a pivot and distinguish a teaching implementation from an in-place one.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Quicksort partitions values around a pivot, then sorts the partitions. Balanced partitions lead to O(n log n) work; repeatedly unbalanced partitions can produce quadratic work and deep recursion. This readable three-way teaching version allocates new lists, so it is not the low-extra-memory in-place partition algorithm sometimes associated with quicksort.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

quick_sort.py
def quicksort(values):
    if len(values) < 2: return list(values)
    pivot = values[len(values) // 2]
    low = [value for value in values if value < pivot]
    equal = [value for value in values if value == pivot]
    high = [value for value in values if value > pivot]
    return quicksort(low) + equal + quicksort(high)
print(quicksort([4, 1, 3, 4, 2]))
↳ EXPECTED OUTPUT
[1, 2, 3, 4, 4]

03 Under the hood

  1. 1

    The pivot separates lower, equal, and higher values. Grouping equal values avoids repeatedly recursing over identical keys.

  2. 2

    Choosing the middle-position value is not the same as finding the median value. It does not guarantee balanced partitions.

  3. 3

    The implementation assumes a consistent total ordering. Special values such as floating-point NaN do not behave like ordinary ordered numbers and can violate its classification assumptions.

04 Your turn, builder

A SMALL MISSION

Check that repeated identical values are retained and an empty input remains empty.

Reveal one possible solution +
one_possible_solution.py
def quicksort(values):
    if len(values) < 2: return list(values)
    pivot = values[len(values) // 2]
    return quicksort([x for x in values if x < pivot]) + [x for x in values if x == pivot] + quicksort([x for x in values if x > pivot])
assert quicksort([2, 2, 2]) == [2, 2, 2]
assert quicksort([]) == []
print("Quicksort checks passed")

05 Check your signal

QUICK SIGNAL CHECK

Does choosing the middle-position pivot guarantee balanced partitions?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.