Sub topic 12
Quick Sort: Partitioning and Worst Case
This chapter assumes you know asymptotic notation, can solve simple recurrences (substitution, recursion tree, Master theorem), and understand merge sort and the sorting properties of stability and in-place behavior. Quick sort is a favorite GATE topic. Questions ask you to trace a partition, state the worst case, or solve a recurrence.
The Idea
Quick sort is a divide-and-conquer sort. It picks one element, the pivot. It rearranges the array so that every element not greater than the pivot is on its left and every larger element is on its right. The pivot is then in its final sorted position. The algorithm sorts the left part and the right part recursively.
Merge sort does its hard work in the combine step (merging). Quick sort does its hard work in the divide step (partitioning). Its combine step does nothing, because the parts are already in the right places.
Lomuto Partitioning
The code below uses the Lomuto scheme with the last element as pivot.
def partition(a, lo, hi):
pivot = a[hi]
i = lo - 1
for j in range(lo, hi):
if a[j] <= pivot:
i += 1
a[i], a[j] = a[j], a[i]
a[i + 1], a[hi] = a[hi], a[i + 1]
return i + 1
def quick_sort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
p = partition(a, lo, hi)
quick_sort(a, lo, p - 1)
quick_sort(a, p + 1, hi)During the loop, the index i marks the end of the "small" region. The array range lo..hi-1 is split into three zones:
lo..i: elements that are at most the pivot.i+1..j-1: elements that are greater than the pivot.j..hi-1: elements not yet examined.
When a[j] <= pivot, the code grows the small zone by one and swaps a[j] into it. After the loop, the pivot swaps into position i + 1, between the two zones. This invariant is what you use to argue correctness.
Worked Trace
Partition [8, 3, 7, 1, 5] with lo = 0, hi = 4. The pivot is 5 and i = -1.
| j | a[j] | a[j] <= 5? | Action | Array after step | i |
|---|---|---|---|---|---|
| 0 | 8 | no | none | 8 3 7 1 5 | -1 |
| 1 | 3 | yes | i=0, swap a[0], a[1] | 3 8 7 1 5 | 0 |
| 2 | 7 | no | none | 3 8 7 1 5 | 0 |
| 3 | 1 | yes | i=1, swap a[1], a[3] | 3 1 7 8 5 | 1 |
The final swap puts the pivot at index i + 1 = 2, which gives [3, 1, 5, 8, 7]. The function returns 2. Everything left of index 2 is at most 5, and everything right is greater than 5. Note that the left part [3, 1] is not sorted yet. Partitioning only places the pivot.
The loop makes exactly hi - lo comparisons, so partitioning n elements costs Theta(n). It uses O(1) extra memory.
The Recurrence
If the pivot lands at position k (so the left part has k elements), then
T(n) = T(k) + T(n - k - 1) + Theta(n).
The cost depends entirely on how balanced the split is.
Worst Case: Theta(n^2)
The worst case occurs when the pivot is always the smallest or largest element. One part has n - 1 elements and the other has 0:
T(n) = T(n - 1) + Theta(n)
Unrolling gives n + (n - 1) + ... + 1 = n(n + 1)/2, which is Theta(n^2). The recursion depth is n, so the stack space is also O(n).
With the last element as pivot, an already sorted array triggers this case, since the last element is the maximum every time. A reverse-sorted array does too, because the last element is the minimum. An array with all equal elements also triggers it with Lomuto, because <= sends every element to the left part.
Best Case: Theta(n log n)
If the pivot is always the median, then T(n) = 2T(n/2) + Theta(n). The Master theorem (case 2) gives Theta(n log n).
Average Case: Theta(n log n)
Even an unbalanced but constant-ratio split stays logarithmic. Suppose every split is 9-to-1:
T(n) = T(9n/10) + T(n/10) + cn
Each level of the recursion tree costs at most cn. The deepest path shrinks by a factor of 9/10 each step, so the depth is log base 10/9 of n. This is still O(log n), so the total is O(n log n). Averaged over all orderings of distinct keys, the expected number of comparisons is about 2n ln n, roughly 1.39 n log2 n.
| Case | Pivot behavior | Recurrence | Time |
|---|---|---|---|
| Best | Median every time | 2T(n/2) + n | Theta(n log n) |
| Average | Random-like splits | Expected over all splits | Theta(n log n) |
| Worst | Min or max every time | T(n-1) + n | Theta(n^2) |
Properties of Quick Sort
- In-place: the partition swaps elements within the array. The only extra memory is the recursion stack.
- Not stable: the long-distance swaps in partitioning can reorder equal keys. For example, sort
[2a, 2b, 1]by key with the last element as pivot. The element2aswaps with1, giving[1, 2b, 2a], and the equal keys have changed order. - Stack space: O(log n) on average, O(n) in the worst case. You can cap the depth at O(log n) by recursing into the smaller part first and looping on the larger part.
- Not adaptive in the basic form: sorted input is the worst case, not the best.
Choosing Pivots
The worst case depends on the pivot rule, not on luck alone. Common fixes:
- Random pivot: swap a random element into position
hibefore partitioning. No fixed input is bad, and the expected time is O(n log n) for every input. - Median of three: use the median of the first, middle, and last elements. This handles sorted and reverse-sorted input well.
- Median of medians: pick the pivot in worst-case linear time, which guarantees O(n log n) overall. The constant factors are large, so it is rarely used in practice.
Even with a good pivot rule, an adversary can build an input that is bad for a specific deterministic rule.
Hoare Partitioning
Hoare's scheme uses two indices that move toward each other from both ends. It swaps out-of-place pairs. It makes fewer swaps on average than Lomuto, but the pivot does not necessarily end up in its final position. GATE questions usually use the Lomuto scheme or describe the partition procedure in the question. Read the code in the question carefully before tracing it.
Common Errors
- Claiming that quick sort is O(n log n) in the worst case. It is O(n^2) unless a worst-case pivot selection is used.
- Believing the partition sorts the sides. It only separates them around the pivot.
- Forgetting that all-equal input is quadratic for Lomuto.
- Calling quick sort stable. It is not.
- Counting the stack as zero. The recursion uses O(log n) to O(n) space.
Exercises
Exercise
Using the Lomuto partition above with the last element as pivot, partition [4, 9, 2, 6, 3]. What is the array afterward, and what index is returned?
Show answer
The pivot is 3 and i = -1. j=0: 4 > 3, skip. j=1: 9 > 3, skip. j=2: 2 <= 3, i=0, swap a[0] and a[2] to get [2, 9, 4, 6, 3]. j=3: 6 > 3, skip. Final swap puts the pivot at i+1 = 1: swap a[1] and a[4] to get [2, 3, 4, 6, 9]. The function returns 1.
Exercise
How many comparisons does quick sort with the last element as pivot make on the sorted array [1, 2, 3, 4, 5]? Give the general formula for n elements.
Show answer
Each partition of m elements makes m - 1 comparisons, and the split is always (m - 1, 0). The total is 4 + 3 + 2 + 1 = 10. In general it is (n - 1) + (n - 2) + ... + 1 = n(n - 1)/2, which is Theta(n^2).
Exercise
A quick sort variant always splits the array in the ratio 1 : 99. What is its asymptotic running time, and why?
Show answer
Theta(n log n). The recurrence is T(n) = T(n/100) + T(99n/100) + cn. Each level of the recursion tree costs at most cn, and the depth is at most log base 100/99 of n, which is O(log n). A constant-ratio split always gives O(n log n).
Exercise
Why is quick sort not stable? Give a three-element example.
Show answer
Partitioning swaps elements across long distances, which can move an element past an equal one. Take [2a, 2b, 1] with the last element as pivot. Only 2a and 2b are compared to 1 and neither is at most 1... in the code, a[j] <= 1 is false for both, so i stays -1. The final swap exchanges a[0] and a[2], giving [1, 2b, 2a]. The equal keys 2a and 2b have swapped order.