Pseudocode (Classic Quick Sort)
Highlighted line matches the current step.
Note: partition(A, l, r) is treated as a black box here.
It rearranges the subarray so that values ≤ pivot go left, values > pivot go right,
and returns the final pivot index k. (Detailed partition steps are covered in the Partition module.)
Time & Space (Quick Look)
Best / Avg: O(n log n)
Balanced partitions (typical case)
Worst: O(n²)
Can occur if partitions are highly unbalanced
Space:
O(log n) avg,
O(n) worst
Recursion depth
Tip: Try an already sorted array with pivot = last to observe deep recursion (worst-case for some deterministic choices).
Why Randomised Quick Sort Helps
When randomisation is better
- Bad input patterns for deterministic pivots: already sorted, reverse sorted, nearly sorted, or repeated patterns.
- Adversarial inputs: when data order might be crafted to trigger worst-case partitions.
- Unknown / unpredictable distributions: random pivots reduce dependency on input order.
Key takeaway
Randomised Quick Sort keeps the same worst-case
O(n²) in theory,
but makes it
very unlikely in practice. The expected running time becomes
Θ(n log n) because partitions are balanced on average.