1123-sorting-algorithmsquicksort — Quicksort
Tutorial
The Problem
Quicksort, invented by Tony Hoare in 1959, is the most widely used sorting algorithm in practice. It achieves O(n log n) average-case time by partitioning around a pivot: elements less than the pivot go left, greater go right, and the sub-arrays are recursively sorted. The in-place variant is cache-friendly and uses O(log n) stack space.
Understanding quicksort deepens understanding of divide-and-conquer, average-case analysis, pivot selection strategies, and why Rust's sort_unstable (which uses a quicksort variant) is faster than sort (which guarantees stability using merge sort).
🎯 Learning Outcomes
sort_unstable uses a pattern-defeating quicksort (pdqsort)Code Example
#![allow(clippy::all)]
//! Stub to satisfy cargo.
pub fn stub() {}Key Differences
sort is stable (merge sort based); sort_unstable (quicksort based) is faster. OCaml's List.sort is stable (merge sort).OCaml Approach
let rec quicksort = function
| [] -> []
| pivot :: rest ->
let smaller = List.filter (fun x -> x <= pivot) rest in
let larger = List.filter (fun x -> x > pivot) rest in
quicksort smaller @ [pivot] @ quicksort larger
This functional quicksort is elegant but O(n) space per level (allocates new lists at each step). For OCaml arrays, an in-place variant uses the same Lomuto/Hoare partitioning as Rust.
Full Source
#![allow(clippy::all)]
//! Stub to satisfy cargo.
pub fn stub() {}Exercises
par_quicksort(arr: &mut [i32]) using rayon for parallel sorting of the two sub-arrays.