Data Structures and Algorithms • C# examples
Randomized Algorithms and Randomized Quicksort
Use randomness to reduce sensitivity to adversarial input while stating the guarantee correctly.
Concept
A randomized algorithm makes random choices as part of its execution. Randomized quicksort chooses a pivot independently of input order, giving expected O(n log n) comparisons under the model, while its worst case remains O(n²). Reproducible seeds help debugging; security-sensitive randomness has different requirements.
How to approach it
Separate expected runtime from worst-case guarantees and choose a random source appropriate to the use.
Complexity
Expected quicksort O(n log n); worst case O(n²).
C# example
int pivotIndex = Random.Shared.Next(low, high + 1);
(items[pivotIndex], items[high]) = (items[high], items[pivotIndex]);
int boundary = Partition(items, low, high);
Expected result or behavior
Random pivot selection reduces correlation between input order and partition quality.
Practice exercise
Explain how a fixed seed changes test reproducibility without changing the algorithm’s correctness.
Key takeaway: Randomization changes probability of costly cases; it does not erase every worst-case bound.