Quick sort
medium 18 minQuick sort picks a pivot, partitions the array so smaller values sit to its left and larger values to its right, and then sorts each side the same way.
See it run
Pick a pivot, partition so smaller values sit left and larger values sit right, then sort each side the same way.
Operations
Lomuto partition
One partition of [8, 3, 7, 4, 9, 2, 6, 5] around the last value, 5. [j] scans left to right; [i] marks the end of the bracketed "< pivot" zone.
Step 1 of 10
Pick the pivot: 5
Lomuto uses the last value as the pivot, so pivot = 5. The goal of one partition: every value smaller than 5 ends up on its left, everything else on its right, and 5 lands in its final sorted slot. i starts at -1: the "< pivot" zone is empty.
Step 1: Pick the pivot: 5
def partition(arr, low, high): pivot = arr[high] # last value is the pivot i = low - 1 # end of the "< pivot" zone for j in range(low, high): # j scans every other value if arr[j] < pivot: # belongs on the left? i += 1 # grow the left zone by one arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] # pivot into the gap return i + 1 # the pivot's final indexarr = [8, 3, 7, 4, 9, 2, 6, 5]print(partition(arr, 0, 7), arr) # 3 [3, 4, 2, 5, 9, 7, 6, 8]- Time
- O(n) per partition
- Space
- O(1)
- this partition
- 7 comparisons, 4 swaps
- always
- n - 1 comparisons
Lomuto in one line: i marks the end of the small zone; every small value found by j is swapped to i + 1; finally the pivot goes to i + 1.
In the real world
The same quick sort doing real jobs. Pick one and step through it.
Pick one book as the reference, move shorter books to its left and taller ones to its right. The reference is now in its final place.
Step 1 of 4
Five books, one reference
Heights in cm: 28, 20, 24, 18, 31. Pick the middle book, 24 cm, as the reference: that is the pivot.
Step 1: Five books, one reference
def shelve(books): if len(books) <= 1: return books ref = books[len(books) // 2] shorter = [b for b in books if b < ref] same = [b for b in books if b == ref] taller = [b for b in books if b > ref] return shelve(shorter) + same + shelve(taller)print(shelve([28, 20, 24, 18, 31])) # [18, 20, 24, 28, 31]Common mistakes
The bugs interviewers watch for, with the fix beside each.
Recursing on p instead of p - 1 (Lomuto)
criticalLomuto puts the pivot in its final slot at p. Including p in the left call means a subarray whose last value is the pivot can partition to the same p forever, which ends in RecursionError.
Wrongp = partition(arr, low, high)quick_sort(arr, low, p) # pivot included againquick_sort(arr, p + 1, high)Rightp = partition(arr, low, high)quick_sort(arr, low, p - 1) # pivot is done: skip itquick_sort(arr, p + 1, high)Using p - 1 with Hoare partition
criticalHoare returns a split point j, not the pivot's final index. The value at j still needs sorting, so skipping it leaves the array unsorted.
Wrongp = hoare_partition(arr, low, high)quick_sort(arr, low, p - 1) # drops arr[p]quick_sort(arr, p + 1, high)Rightp = hoare_partition(arr, low, high)quick_sort(arr, low, p) # [low..j]quick_sort(arr, p + 1, high) # [j+1..high]Last-value pivot on sorted input
majorOn sorted or nearly sorted data the last value is the maximum, every split is n-1 | 0, the time is O(n²), and the recursion is n deep. In Python that hits the 1000-frame recursion limit on a sorted list of a few thousand values.
Wrongpivot = arr[high] # always the last valueRightr = random.randint(low, high) # random pivotarr[r], arr[high] = arr[high], arr[r]pivot = arr[high]Losing duplicates in the list version
criticalThe short list-comprehension version must keep values equal to the pivot. Filtering only < and > throws away every copy of the pivot except one.
Wrongleft = [x for x in arr if x < p]right = [x for x in arr if x > p]return qs(left) + [p] + qs(right) # [3, 3, 1] -> [1, 3]Rightleft = [x for x in arr if x < p]mid = [x for x in arr if x == p]right = [x for x in arr if x > p]return qs(left) + mid + qs(right)Recursing on both sides blindly
majorWith bad splits the stack grows to n frames. Recursing only into the smaller side and looping on the larger one caps the depth at log2 n, whatever the pivots.
Wrongdef quick_sort(arr, low, high): if low < high: p = partition(arr, low, high) quick_sort(arr, low, p - 1) quick_sort(arr, p + 1, high)Rightdef quick_sort(arr, low, high): while low < high: p = partition(arr, low, high) if p - low < high - p: quick_sort(arr, low, p - 1) # smaller side: recurse low = p + 1 # larger side: loop else: quick_sort(arr, p + 1, high) high = p - 1Forgetting the base case
criticalWithout the low < high check, calls on empty or one-value ranges keep partitioning and recursing until the stack overflows.
Wrongdef quick_sort(arr, low, high): p = partition(arr, low, high) quick_sort(arr, low, p - 1) quick_sort(arr, p + 1, high)Rightdef quick_sort(arr, low, high): if low < high: # 0 or 1 values: stop p = partition(arr, low, high) quick_sort(arr, low, p - 1) quick_sort(arr, p + 1, high)
Interview tips
How to explain it
- Pick a pivot, partition so smaller values go left and larger go right, then recurse on both sides.
- After one partition the pivot is in its final sorted position.
- Best and average O(n log n), worst O(n²) when the pivot is always the min or max.
- In place, O(log n) stack on average, not stable.
Spot it in the wild
- General-purpose in-memory sorting of arrays of numbers.
- Find the k-th smallest or largest value: quickselect, O(n) on average.
- Three-way partitioning: sort colours, group by category, many duplicate keys.
Memory tricks
- PPSR: Pick a pivot, Partition, Sort the left, Recurse on the right.
- Quick sort works on the way down, merge sort on the way up.
- Bad pivot, bad day: always min or max means n squared.
Watch out
- Lomuto recurses on p - 1 and p + 1; Hoare on p and p + 1.
- Last-value pivot plus sorted input is the worst case.
- Keep the values equal to the pivot when you write the list version.