3.6.3 · D3Sorting & Searching

Worked examples — Quick sort — Lomuto - Hoare partition, pivot strategies, expected O(n log n), worst case

2,638 words12 min readBack to topic

The scenario matrix

Every quicksort question is really one of these cells. The examples below are labelled with the cell they cover.

# Cell class What makes it special Which partition breaks / shines
C1 Random / generic array typical case, splits are unbalanced-ish Lomuto & Hoare both fine,
C2 Already sorted (ascending) last-element pivot is always the max Lomuto → worst case
C3 Reverse sorted last-element pivot is always the min Lomuto → worst case
C4 All elements equal every comparison is a "tie" Lomuto → ; 3-way →
C5 Degenerate size () base case / smallest real work tests the recursion boundary
C6 Hoare vs Lomuto same input Hoare returns a boundary, not pivot index shows the recursion-index trap
C7 Median-of-three defense sorted input made harmless shows why the trick works
C8 Word problem (leaderboard) real numbers, real question expected comparisons formula
C9 Exam twist (count comparisons) uses and the split recurrence the "derive it" cell

C1 — Random array (Lomuto, the typical case)


C2 — Already sorted array (Lomuto worst case)


C3 — Reverse sorted (still worst case, opposite peel)


C4 — All elements equal (the duplicate trap)


C5 — Degenerate sizes (the base cases)


C6 — Hoare vs Lomuto on the same input (the index trap)


C7 — Median-of-three defense on sorted input


C8 — Word problem (expected comparisons)


C9 — Exam twist (bound the 9-to-1 split)


Recall Self-test (reveal after guessing)

Lomuto on already-sorted [1,2,3,4] — comparison count? ::: , i.e. . Hoare returns index j; which recursion calls do you make? ::: quicksort(lo, j) and quicksort(j+1, hi) — never j-1/j+1. All-equal array with plain Lomuto — best or worst case? ::: Worst, ; fix with 3-way partitioning. Expected comparisons to sort 1000 distinct items? ::: . Median-of-three pivot for sorted [1..7]? ::: median of {1,4,7} = 4 → perfect 3/3 split.

See also: Merge Sort, Heap Sort, Quickselect, Randomized Algorithms, Master Theorem, Binary Search.