Part IA Lent Term
Quicksort: Algorithm
Divide-and-Conquer Structure
Quicksort is a recursive divide-and-conquer sort:
- Divide: Choose a pivot element from the array. Partition (rearrange) the array so that all elements pivot come before it and all elements pivot come after it.
- Conquer: Recursively sort the left and right subarrays (excluding the pivot, which is now in its correct final position).
- Combine: Nothing to do — the pivot placement plus recursively sorted subarrays yields a fully sorted array.
Lomuto Partitioning
The standard partition scheme (Lomuto) picks the last element as pivot:
x = A[r](pivot is last element)i = p - 1(boundary of ” pivot” region)- For
j = ptor-1: - If
A[j] <= x: -
i = i + 1 - Swap
A[i]andA[j] - Swap
A[i+1]andA[r](place pivot in correct position) - Return
i+1(pivot’s index)
At any point, the array is partitioned as:
Walkthrough Example
Array: with pivot
| Step | j | Condition | Action | Result |
|---|---|---|---|---|
| Init | — | — | i = -1, pivot = 4 | |
| 1 | 0 | Nothing | ||
| 2 | 1 | i=0, swap A[0],A[1] | ||
| 3 | 2 | i=1, swap A[1],A[2] | ||
| 4 | 3 | Nothing | ||
| 5 | 4 | i=2, swap A[2],A[4] | ||
| Final | — | — | swap A[3],A[5] |
Pivot 4 is at index 3. Left subarray and right subarray are recursively sorted.
Hoare Partitioning (Alternative)
Hoare’s scheme uses two pointers moving inward from both ends, swapping out-of-order pairs. It typically performs fewer swaps than Lomuto, and the pivot ends up somewhere in the middle but not necessarily at the returned index.
Pivot Selection Strategies
| Strategy | Effect |
|---|---|
| First element | Simple; worst case on sorted input |
| Last element | Simple; worst case on reverse-sorted input |
| Random | Expected ; eliminates adversarial inputs |
| Median-of-three | Pivot is median of A[p], A[mid], A[r]; reduces worst-case probability |
| Median-of-medians | Guaranteed worst case; high constant factor |
The choice of pivot is the single most important factor affecting Quicksort’s performance. A poor pivot (extreme min or max) produces an to 1 split and degrades to . A good pivot (median) gives balanced splits and .
Properties
| Property | Value |
|---|---|
| In-place | Yes ( stack space for recursion) |
| Stable | No — partitioning swaps non-adjacent elements |
| Divide step | (one scan of subarray) |
| Combine step | No work required |