3.6.4 · D3Sorting & Searching

Worked examples — Quick sort randomization — expected O(n log n)

3,825 words17 min readBack to topic

Before we start, one reminder of the single formula everything below uses. From the parent note:

The key numbers here are the gap (how far apart two elements sit in sorted order) and the resulting probability . Notice: the probability depends only on the gap, never on the actual values or where the elements started. Keep that in your pocket.


The scenario matrix

Every question this topic can throw at you falls into one of these cells. The worked examples below are labelled with the cell (C1–C9) they cover.

Cell Scenario class What's tricky about it Example
C1 Smallest non-trivial array () Are adjacent elements always compared? Ex 1
C2 Full expected count for small Grouping pairs by gap Ex 2
C3 Gap extremes — adjacent () vs far ( max) vs tiny Ex 3
C4 "Adversary" sorted / reverse-sorted input Does input order change the answer? Ex 4
C5 Degenerate: and Zero comparisons, base case Ex 5
C6 Duplicates / equal keys Does "sorted order" still make sense? Ex 6
C7 Limiting behaviour (large ) , ratio to Ex 7
C8 Real-world word problem Translate a story into the formula Ex 8
C9 Exam twist — conditional / "given first pivot" Reasoning under a condition Ex 9

Worked examples

Ex 1 — smallest non-trivial arrays (Cell C1)


Ex 2 — the full count for (Cell C2)


Ex 3 — gap extremes side by side (Cell C3)


Ex 4 — the "adversary" input (Cell C4)


Ex 5 — degenerate inputs and (Cell C5)


Ex 6 — duplicate keys (Cell C6)


Ex 7 — limiting behaviour for large (Cell C7)


Ex 8 — real-world word problem (Cell C8)


Ex 9 — exam twist: conditional probability (Cell C9)


Active recall

Recall Which matrix cell does each fact hit? (open after attempting)

Adjacent elements () are compared with probability… ::: exactly (Cell C3/C1). for … ::: comparisons (Cell C2). Does sorted input raise for randomized quicksort? ::: No — the formula ignores input order; still for (Cell C4). for or … ::: (empty sum, Cell C5). Do duplicate keys break the analysis? ::: No — tie-break by index; the distinct-key formula is an upper bound (Cell C6). Exact closed form for ? ::: (Cell C7). Ratio as … ::: tends to (Cell C7). Given the whole array's first pivot is a middle element with , … ::: — they are split apart forever (Cell C9).