Quicksort in Python
A divide-and-conquer sort that is short to write and fast in practice.
def quicksort(items):
if len(items) <= 1:
return items
pivot = items[len(items) // 2]
left = [x for x in items if x < pivot]
mid = [x for x in items if x == pivot]
right = [x for x in items if x > pivot]
return quicksort(left) + mid + quicksort(right)
How it works
- Picks the middle element as a pivot.
- List comprehensions split values below, equal to, and above the pivot.
- Recursively sorts both sides and stitches the three parts together.
Keywords and builtins used here
defforiflenquicksortreturn
The run, in numbers
- Lines
- 8
- Characters to type
- 251
- Tokens
- 80
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 48 seconds.
Step 3 of 5 in Algorithms, step 53 of 72 in Language basics.