Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
Seven kids line up for the class photo. Tom steps out, shorter kids go left, taller go right, and Tom's spot is final. Ten compares for seven kids, about 24 million for a million, and 124,750 for 500 kids already in order.
What you will learn
- Explain quick sort with a pivot friend: shorter left, taller right
- Trace one partition round compare by compare and see the pivot land in its final spot
- Say why a fair split gives O(n log n) and a line already in order gives O(n²)
- Fix the sorted-input problem by picking the middle element as the pivot
Before you start
- Recursion
- Merge Sort
It's photo day, and seven kids stand in a line with their heights in centimetres: Emma 158, Jack 135, Kate 147, Liam 162, Lucy 141, Mark 170 and Tom 150, last in line. The photographer wants the shortest on the left and the tallest on the right. Seven kids now, maybe a million later. In code, each kid is just a height in a list, and you sort that list.
Line up around one friend
Tom steps out. He's the friend, and every kid checks their height against Tom. Shorter than Tom? Go left. Taller? Go right. Then Tom steps into the gap.
Here's the interesting part: Tom's spot is final. Everyone on his left is shorter and everyone on his right is taller, so whatever happens next, he never has to move again. Then each side does the same trick with its own friend, and the two sides don't need each other any more.
The friend is called the pivot, sending kids left and right is the partition, and doing it again on each side is recursion. Pick a friend, shorter left, taller right, then the same trick on each side. That's quick sort.
Play the sort
Positions count from 0. spot is where the next shorter kid goes; it starts at 0.
- 158 shorter than 150? No. Emma stays.
- 135? Yes. Jack swaps into the spot, and the spot moves to 1.
- 147? Yes. Kate swaps in; the spot is 2.
- 162? No. Liam stays.
- 141? Yes. Lucy swaps in; the spot is 3.
- 170? No. Mark stays.
- Everyone's checked. Tom swaps with Liam and steps into position 3. Final.
The shorter side does the same: Lucy (141) is the friend, Jack goes left, Kate goes right, and Lucy lands at position 1. The taller side too: Liam (162) is the friend, Emma goes left, Mark goes right, and Liam lands at position 5. Every part left has one kid, and one kid is already sorted. Done, in ten compares.
The code
compares = 0
def place(a, lo, hi):
global compares
pivot = a[hi] # the friend: last in line
spot = lo # where a shorter kid goes
for j in range(lo, hi):
compares += 1
if a[j] < pivot:
swap(a, j, spot)
spot += 1
swap(a, spot, hi) # the friend steps in
return spot
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
That's one round, the partition: one walk down the line, and the friend ends in his final place.
import pivot
trace = True
def sort(a, lo, hi):
if lo >= hi:
return # 0 or 1 kid: done
p = pivot.place(a, lo, hi) # the friend's spot
if trace:
print("pivot " + str(a[p]) + ": " + str(a))
sort(a, lo, p - 1) # the shorter side
sort(a, p + 1, hi) # the taller side
Zero or one kid is already sorted, so stop. Otherwise run one round, then sort the shorter side and the taller side. sort calls itself on each side.
import quick_sort
# Emma, Jack, Kate, Liam, Lucy, Mark, Tom
heights = [158, 135, 147, 162, 141, 170, 150]
print("Before: " + str(heights))
quick_sort.sort(heights, 0, len(heights) - 1)
print("After: " + str(heights))
Before: [158, 135, 147, 162, 141, 170, 150]
pivot 150: [135, 147, 141, 150, 158, 170, 162]
pivot 141: [135, 141, 147, 150, 158, 170, 162]
pivot 162: [135, 141, 147, 150, 158, 162, 170]
After: [135, 141, 147, 150, 158, 162, 170]
Three pivot lines, each one a friend finding his spot.
A million kids
import random
import pivot
import quick_sort
quick_sort.trace = False
random.seed(7)
for n in (1_000, 10_000, 100_000, 1_000_000):
heights = [0] * n
for i in range(n):
heights[i] = random.randint(0, 2_000_000_000)
pivot.compares = 0
quick_sort.sort(heights, 0, n - 1)
print(f"{n:9,d} kids: {pivot.compares:11,d} compares")
1,000 kids: 11,518 compares
10,000 kids: 162,436 compares
100,000 kids: 2,014,418 compares
1,000,000 kids: 24,459,926 compares
Why so few? Each walk checks every kid once and cuts the line into two parts. Eight kids: 8, 4, 2, and after three walks every part is one kid. A million kids: after about twenty walks every part is down to one. Twenty walks over a million kids is around twenty million compares, and in practice it's about twenty-five million because the splits are never perfect. Everyone against everyone would be half a million million.
Break it: a line already in order
import pivot
import quick_sort
quick_sort.trace = False
n = 500
heights = [0] * n
for i in range(n):
heights[i] = 100 + i # already in order
quick_sort.sort(heights, 0, n - 1)
print(f"{n:,d} kids in order: {pivot.compares:,d} compares")
500 kids in order: 124,750 compares
Over a hundred and twenty thousand compares for 500 kids. Why? With the same seven kids in order, Mark (170) is last, so he's the friend. Every kid is shorter, so all six go left and nobody goes right: six compares, and only Mark is placed. Then Liam is the tallest of the six: five compares, one kid placed. Then four, three, two, one. Twenty-one compares for seven kids, where the mixed line needed ten. The friend was always the tallest, so each round placed just one kid.
The fix: pick the middle kid
Use the middle kid as the friend instead. On the sorted line that's Tom, and the split is fair: three shorter kids on the left, three taller on the right. Each side picks its own middle kid too, so seven kids need only ten compares, not twenty-one. For ten thousand kids in order, the middle kid brings it down from about fifty million compares to about one hundred and fourteen thousand.
The cost
| Case | Cost |
|---|---|
| One round (partition) | O(n), one walk down the part |
| Fair splits (random line) | O(n log n), about log n rounds deep |
| Line already in order, last kid as pivot | O(n²) |
| Extra room | none for the line itself; it sorts in place |
The size of the line matters, but the fairness of the split matters even more. Python's own sorted isn't a quick sort: it's a tuned merge sort called Timsort, so a sorted line is no problem for it.
Where you meet quick sort
- The built-in sort in many languages uses a tuned quick sort for lists of numbers, with a smarter way to pick the friend.
- A database sorting a shop's products by price often uses quick sort when everything fits in memory.
- Finding the median of a million readings: split at a friend and follow only the side that holds the middle.
- Sorting on many computers: after one split, the two sides are independent, so two workers can sort them at the same time.
Try it yourself
In place, use the middle kid as the friend: swap a[(lo + hi) // 2] with a[hi] first. Then run the 500-kids-in-order example again and compare the count.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
