Sub topic 11
Quick Sort: Partitioning and Worst Case
Assume you know arrays, recursion, logarithms, and basic recurrence relations. Quick sort is a comparison-based sorting algorithm that rearranges an array around a chosen pivot.
Partitioning
A partition operation places the pivot in its final sorted position. Every element on its left is less than or equal to it, and every element on its right is greater than it. The two sides are then sorted recursively.
The following implementation uses Lomuto partitioning. It chooses the last element as the 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)
values = [7, 2, 9, 4, 1, 5]
quick_sort(values)
print(values)During partitioning, i marks the end of the region containing elements no greater than the pivot. After the loop, swapping the pivot with a[i + 1] places it correctly.
Time Complexity
Partitioning a subarray of size \(n\) takes Θ(\(n\)) time. If the pivot divides the array into parts of sizes \(k\) and \(n-k-1\), the recurrence is:
\[ T(n) = T(k) + T(n-k-1) + \Theta(n) \]
| Pivot split | Recurrence behavior | Running time |
|---|---|---|
| Nearly equal halves | \(2T(n/2) + \Theta(n)\) | Θ(\(n \log n\)) |
| One empty side | \(T(n-1) + \Theta(n)\) | Θ(\(n^2\)) |
| Typical randomized split | Varies by split | Expected Θ(\(n \log n\)) |
The best case occurs when each pivot divides the remaining array into nearly equal halves. The worst case occurs when the pivot is always the smallest or largest element. With the last-element rule, an already sorted array produces this worst case.
Practical Properties and GATE Patterns
Quick sort is usually in-place because partitioning uses only constant auxiliary space. However, recursive calls require stack space. Balanced recursion uses Θ(\(\log n\)) stack space, while worst-case recursion uses Θ(\(n\)) space.
Basic quick sort is not stable. Equal elements may change their relative order during swaps. Randomized pivots or median-based choices reduce the chance of consistently poor splits but do not change the worst-case bound.
Exercise
What is the worst-case time complexity of Lomuto quick sort when the pivot is always the largest element?
Show answer
The recurrence is T(n) = T(n - 1) + Θ(n), so the time complexity is Θ(n²).