Quicksort & quickselect
Implement quicksort with a good pivot strategy and find the k-th element with quickselect.
By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.
In short
Quicksort picks a pivot, partitions the array into elements smaller and larger than it, then recursively sorts each side. It sorts in place and is very fast in practice, averaging O(n log n). A poor pivot on sorted input gives O(n^2), so pivots are chosen randomly or by median-of-three.
Explained simply
Quicksort picks one item called the pivot. It then rearranges the list so that every item smaller than the pivot is on its left and every larger item is on its right. Now the pivot is in its final place. Repeat the same thing on the left part and the right part.
Picture a teacher lining up students by height. She picks one student, says "shorter ones stand to my left, taller to my right", and then does the same for each group. Each group shrinks until every group has one student.
If the pivot lands near the middle each time, the groups halve, and the whole sort takes about n log n steps. If the pivot is always the smallest or largest item, one group is empty and the other barely shrinks. Then it takes about n^2 steps. Picking the pivot at random makes that bad case extremely unlikely.
Quicksort sorts in place, using very little extra memory, and it is fast on real computers. A close relative, quickselect, uses the same splitting to find, for example, the median or the 10th smallest item without sorting everything.
Press Play on a diagram to walk through it one step at a time.
- 1Pick pivot
Here the last element.
- 2Scan
j moves left to right.
- 3Swap small
If a[j] < pivot, swap into the left region.
- 4Place pivot
Swap pivot after the left region.
- 5Recurse
Sort both sides of the pivot.
- k == 2: answer is 4
- Only one partition needed
- If k were 0 or 1
- Recurse into [2, 1] only
- If k were 3 or 4
- Recurse into [7, 9] only
In depth
Lomuto versus Hoare partitioning
Lomuto partition uses the last element as pivot and one write index i. Scan j from left to right; whenever a[j] < pivot, swap it into position i and advance i. Finally swap the pivot into position i. It is simple and returns the pivot's final index.
Hoare partition uses two indexes moving towards each other. The left one moves right while items are less than the pivot; the right one moves left while items are greater. When both stop, swap the two items and continue until the indexes cross. On average Hoare does about three times fewer swaps than Lomuto and handles many equal keys better, because equal items stop both scans and get spread across both sides.
The catch with Hoare: the pivot does not necessarily end up in its final position, and the function returns a split point j. You then recurse on a[lo..j] and a[j+1..hi], not on j - 1.
- Lomuto: one scan, pivot placed exactly, more swaps
- Hoare: two scans inward, fewer swaps, recurse on [lo, j] and [j+1, hi]
- Both: O(n) time per partition, O(1) extra space
- Pivot = last element
- One pointer scans left to right
- Returns pivot's final index
- Degrades to O(n^2) on all-equal keys
- Pivot = middle or first element
- Two pointers move inward
- Returns a split point, not the pivot index
- Splits equal keys evenly
Why the worst case is O(n^2), and how to avoid it
Each partition costs O(n). If the pivot splits the array into sizes n - 1 and 0, the recurrence becomes T(n) = T(n - 1) + O(n), which sums to n(n - 1)/2 comparisons: quadratic. With a last-element pivot this happens on already sorted or reversed input, which is very common in practice.
Random pivots fix this in expectation. The expected number of comparisons is about 2n ln n, roughly 1.39 n log2 n, for every input. No specific input is bad; only unlucky coin flips are, and the chance of quadratic behaviour on large inputs is tiny.
Median-of-three takes the median of the first, middle and last elements. It handles sorted input well and gives slightly better splits, but crafted inputs can still defeat it. That is why C++ std::sort uses introsort: quicksort that switches to heapsort if recursion gets deeper than about 2 log2 n, guaranteeing O(n log n).
- Bad split every time: T(n) = T(n-1) + O(n) = O(n^2)
- Random pivot: about 1.39 n log2 n expected comparisons
- Introsort caps the worst case at O(n log n)
Duplicates and three-way partitioning
If many keys are equal, Lomuto puts all items equal to the pivot on one side. An array of all equal values then produces the worst-case split every time: O(n^2).
Three-way partitioning, also known as the Dutch national flag method, splits into three regions: less than, equal to, and greater than the pivot. Keep three indexes lt, i and gt. If a[i] < pivot, swap it to the lt region and advance both. If greater, swap it with a[gt] and shrink gt (do not advance i, because the swapped-in item is unchecked). If equal, just advance i. Then recurse only on the less and greater regions.
With few distinct values, this approaches O(n) per distinct value. Java's sort for primitive arrays uses a dual-pivot quicksort that also groups equal elements well.
- 1a[lo..lt-1]
Less than pivot.
- 2a[lt..i-1]
Equal to pivot.
- 3a[i..gt]
Not yet examined.
- 4a[gt+1..hi]
Greater than pivot.
- 5Recurse
Only on the less and greater regions.
Stack depth and practical tuning
Quicksort's stack depth is O(log n) on average, but O(n) in the worst case, which in Python means RecursionError for large bad inputs. A standard fix: recurse into the smaller side and loop on the larger side. The smaller side is at most half the size, so the depth is at most log2 n, even with bad pivots.
Other tuning used by library sorts: stop recursing on small ranges (around 16 elements) and finish with insertion sort; choose pivots by median-of-three or a sample; and use three-way partitioning when duplicates are common.
Quicksort is not stable: partitioning swaps items over long distances. If you need stability, use merge sort or Timsort. In Python you will rarely write quicksort for production, because sorted() is implemented in C and is faster. You write it to understand partitioning, which powers quickselect and many array problems.
- Recurse on the smaller side: depth at most log2 n
- Insertion sort below about 16 items
- Not stable
Quickselect for the k-th smallest
After partitioning, the pivot is at its final sorted index p. If p equals k, you are done. If k < p, the answer is on the left; otherwise on the right. Unlike quicksort, you recurse into only one side.
With random pivots, the expected work is n + n/2 + n/4 + ... which is O(n), between about 2n and 3.4n comparisons depending on k. The worst case is still O(n^2). The median-of-medians algorithm picks a pivot guaranteed to be near the middle and gives O(n) worst case, but its constant factor is large, so it is rarely used directly.
Alternatives in Python: heapq.nsmallest(k, a) runs in O(n log k) and is great for small k. sorted(a)[k] is O(n log n) and often fastest for moderate sizes because it runs in C. statistics.median sorts the data. numpy.partition implements introselect if you use NumPy.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Partition with Lomuto and Hoare schemes~45m
- 2Choose random or median-of-three pivots~45m
- 3Explain the O(n^2) worst case~45m
- 4Find the k-th smallest with quickselect~45m
Key points
- Average O(n log n), worst O(n^2), O(log n) stack on average.
- Not stable in its usual in-place form.
- Random pivots make the worst case extremely unlikely.
- Quickselect finds the k-th smallest in O(n) average by recursing into one side.
Key terms
Tap a card to flip it. 0/4 known
Examples
import random
def quicksort(a, lo=0, hi=None): # average O(n log n)
if hi is None: hi = len(a) - 1
if lo >= hi: return a
p = random.randint(lo, hi)
a[p], a[hi] = a[hi], a[p]
i = lo
for j in range(lo, hi):
if a[j] < a[hi]:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
quicksort(a, lo, i - 1); quicksort(a, i + 1, hi)
return aHoare partition with tail-call elimination
This quicksort uses Hoare's scheme. It swaps a random element to the front and uses it as the pivot (a pivot taken from the last slot can make Hoare return hi and loop forever). Then it recurses into the smaller part and loops on the larger part. It sorts the list in place. The while loop replaces the second recursive call, so stack depth stays at most log2 n even with unlucky pivots.
import random
def quicksort(a, lo, hi):
while lo < hi:
r = random.randint(lo, hi); a[lo], a[r] = a[r], a[lo]
p, i, j = a[lo], lo - 1, hi + 1
while True:
i += 1
while a[i] < p: i += 1
j -= 1
while a[j] > p: j -= 1
if i >= j: break
a[i], a[j] = a[j], a[i]
if j - lo < hi - j: quicksort(a, lo, j); lo = j + 1
else: quicksort(a, j + 1, hi); hi = j
a = [3, 8, 2, 5, 1, 4, 7, 6]; quicksort(a, 0, len(a) - 1); print(a)Quickselect: the k-th smallest in expected O(n)
To find the median of 101 numbers we need k = 50 (0-based). Each round partitions around a random pivot with a three-way split into less, equal and greater lists. If k falls inside the equal block, we return the pivot. Otherwise we keep only the side containing k and adjust k. This version builds new lists for clarity; an in-place version uses the Lomuto partition from the explainer.
import random
def quickselect(a, k):
while True:
p = random.choice(a)
less = [x for x in a if x < p]
equal = a.count(p)
if k < len(less):
a = less
elif k < len(less) + equal:
return p
else:
k -= len(less) + equal
a = [x for x in a if x > p]
print(quickselect([7, 2, 9, 4, 1], 2)) # 4Quick reference
- Average O(n log n), worst O(n^2), in-place, not stable
- Random pivot: about 1.39 n log2 n expected comparisons on any input
- Lomuto: recurse on [lo, p-1] and [p+1, hi]; Hoare: on [lo, j] and [j+1, hi]
- Many duplicates: three-way partition into <, ==, >
- Recurse on the smaller side and loop on the larger: stack O(log n)
- Quickselect: expected O(n), worst O(n^2); median of medians: O(n) worst
- Small k: heapq.nsmallest(k, a) in O(n log k)
Common mistakes
- Always using the first or last element as pivot on sorted input.
- Many duplicates degrade Lomuto; use three-way partitioning.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write lomuto(a, lo, hi) that partitions a[lo..hi] around a[hi] and returns the pivot's final index. Example: on [4, 7, 2, 6, 5] it returns 2 and the list becomes [4, 2, 5, 6, 7].
- Exercise 2medium
Write sort_colors(a) that sorts a list of 0s, 1s and 2s in one pass and in place (Dutch national flag). Example: [2, 0, 2, 1, 1, 0] becomes [0, 0, 1, 1, 2, 2].
- Exercise 3hard
Write kth_largest(a, k) in place with quickselect using the lomuto function and a random pivot, in expected O(n). Example: kth_largest([3, 2, 1, 5, 6, 4], 2) is 5.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why is it called quicksort if its worst case is O(n^2)?
- In practice it is very fast: it works in place, has a tight inner loop and good cache behaviour. With random or well-chosen pivots the quadratic case is extremely unlikely.
- Is quicksort stable?
- No. Partitioning swaps items across long distances, so equal items can change order. Use merge sort or Python's sorted() when stability matters.
- What is the fastest way to get the median in Python?
- statistics.median(a) is simple and runs in O(n log n) because it sorts. For huge arrays, numpy.median or numpy.partition use a selection algorithm and are much faster.