Worked Examples: Quicksort & Selection

These examples are designed to step through the logical process of applying Quicksort and related algorithms.

Example 1: Lomuto Partition Trace
❓ Problem: Partition [2, 8, 7, 1, 3, 5, 6, 4] using Lomuto with pivot 4 (last element).
💡 Solution: i starts at -1. Scan j=0 to 6. When A[j] ≤ 4, increment i and swap. Elements 2, 1, 3 move left. Final swap puts pivot at index 3. Result: [2, 1, 3, 4, 8, 5, 6, 7]. Return index 3.
Example 2: Hoare Partition Trace
❓ Problem: Partition [4, 8, 7, 1, 3, 5, 2, 6] using Hoare with pivot 4 (first element).
💡 Solution: i scans right for ≥4, j scans left for ≤4. i finds 4, j finds 2. Swap → [2, 8, 7, 1, 3, 5, 4, 6]. i finds 8, j finds 3. Swap → [2, 3, 7, 1, 8, 5, 4, 6]. Continue until i > j. Return j as partition point.
Example 3: Worst Case Input
❓ Problem: What input causes $O(n^2)$ time for Quicksort with last-element pivot?
💡 Solution: Already sorted [1,2,3,4,5] or reverse sorted [5,4,3,2,1]. Each partition creates 0 and n-1 splits. Recurrence: T(n) = T(n-1) + n = $O(n^2)$.
Example 4: Best Case Analysis
❓ Problem: What is Quicksort's best case and when does it occur?
💡 Solution: Best case is $O(n \log n)$ when pivot always splits array in half. Recurrence: T(n) = 2T(n/2) + n. Even 10-90 splits give $O(n \log n)$ due to log depth.
Example 5: QuickSelect for k-th Smallest
❓ Problem: Find 3rd smallest in [7, 10, 4, 3, 20, 15].
💡 Solution: Partition with pivot=15: [7, 10, 4, 3, 15, 20]. Pivot at index 4. k=3 < 4, so recurse left [7, 10, 4, 3]. Partition with pivot=3: [3, 10, 4, 7]. Pivot at 0. k=3 > 0, recurse right. Continue until k matches pivot position. Answer: 7.
Example 6: Randomized Quicksort
❓ Problem: Why does randomized pivot selection help?
💡 Solution: No adversary can craft worst-case input since pivot is random. Expected time is $O(n \log n)$. Probability of consistently bad pivots is $(1/n!)$, essentially zero.